Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose home assistant jinja template functions #568

Open
austinche opened this issue Jan 8, 2024 · 1 comment
Open

Expose home assistant jinja template functions #568

austinche opened this issue Jan 8, 2024 · 1 comment

Comments

@austinche
Copy link

One thing missing from pyscript compared with regular home assistant scripts and automations is access to the capabilities provided by the jinja template extensions such as working with areas and devices. As described in #251, it is possible to provide pyscript access to the template functions. The following code exposes all functions that take the hass object (https://www.home-assistant.io/docs/configuration/templating/).

With the following in modules/template.py and after import template you can call any of these functions like template.device_entities(device_id).

import homeassistant.helpers.template as template

hass_template_functions = [
    'device_entities', 
    'device_attr', 
    'is_device_attr', 
    'config_entry_id', 
    'device_id', 
    'areas', 
    'area_id',
    'area_name',
    'area_entities',
    'area_devices', 
    'integration_entities',
    'expand',
    'closest',
    'distance',
    'is_hidden_entity',
    'is_state',
    'is_state_attr',
    'state_attr',
    'has_value',
    'utcnow',
    'now',
    'relative_time',
    'today_at',
]

def hass_template_wrap(fn_name):
    def wrap(*args, **kwargs):
        return getattr(template, fn_name)(hass, *args, **kwargs)
    return wrap

for fn in hass_template_functions:
    globals()[fn] = hass_template_wrap(fn)

This is pretty generic, easily maintainable, and feels like it should be part of pyscript core. It would eliminate a large part of the need to enable access to hass as a global variable or allowing all imports and makes it more straightforward to port any existing automation to pyscript.

@ALERTua
Copy link
Contributor

ALERTua commented Jan 8, 2024

Maybe you could create a few usage examples and maybe create a pull request to support templating?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants