custom-components / pyscript

Pyscript adds rich Python scripting to HASS
Apache License 2.0
873 stars 46 forks source link

Template evaluation #589

Open SVH-Powel opened 7 months ago

SVH-Powel commented 7 months ago

This is a feature request

Make it possible to evaluate templates in pyscript. Preferable with a function call that takes the template as a parameter and return the value from the evaluation.

https://community.home-assistant.io/t/pyscript-new-integration-for-easy-and-powerful-python-scripting/215967/304

ALERTua commented 7 months ago

with from homeassistant.helpers.template import Template you can instantiate Template('{{ states('light.office') == 'off' }}', hass) and .async_render() it and get your result :)

import homeassistant.helpers.template as template

@service
def tryouts(trigger_type=None, var_name=None, value=None, old_value=None, context=None, **kwargs):
    templ = template.Template("{{ states('light.office') == 'off' }}", hass)
    result = templ.async_render()
    log.debug(f"{templ}: {result}")

Calling pyscript.tryouts service results in this log entry Template<template=({{ states('light.office') == 'off' }}) renders=1>: True

SVH-Powel commented 7 months ago

with from homeassistant.helpers.template import Template you can instantiate Template('{{ states('light.office') == 'off' }}', hass) and .async_render() it and get your result :)

import homeassistant.helpers.template as template

@service
def tryouts(trigger_type=None, var_name=None, value=None, old_value=None, context=None, **kwargs):
    templ = template.Template("{{ states('light.office') == 'off' }}", hass)
    result = templ.async_render()
    log.debug(f"{templ}: {result}")

Calling pyscript.tryouts service results in this log entry Template<template=({{ states('light.office') == 'off' }}) renders=1>: True

Thanks. But still, I think this would be a nice feature without having to enable hass as a global variable.