Thanks to the new jinja documentation, I learned about custom filters and the apply function. Experimenting with it, I discovered that apply doesn’t work with specific Home Assistant functions/tests, such as has_value, states, is_state, etc.
Specifically, apply doesn’t seem to pass the first argument named “value” to these functions. I wonder if this isn’t some legacy thing, as there’s no obvious visible difference in how HA-specific functions accept arguments vs. built-in functions.
Below is an example comparing the built-in float function and the special state_attr function (both accept 2 arguments).
- Standard function call:
{{ float('abc',5) }} {# result: 5 #}
{{ state_attr('sun.sun','elevation') }} {# result: 41.54 #}
- Call via apply:
{{ apply('abc',float,5) }} {# result: 5 #}
{{ apply('sun.sun',state_attr,'elevation') }} {# result: TypeError: state_attr() missing 1 required positional argument: 'name' #}
The value argument of apply (‘sun_sun’) was ignored and ‘elevation’ was passed to state_attr as entity_id. I can confirm it with:
{{ apply('sun.sun',state_attr,'sun.sun','elevation') }} {# result: 41.54 #}
{{ apply('this is ignored',state_attr,'sun.sun','elevation') }} {# result: 41.54 #}
- Passing arguments
Now to the more important stuff (I think). A more general way of passing arguments also works with HA-specific functions:
{{ state_attr(*['sun.sun','elevation']) }}
{{ state_attr(**{'entity_id':'sun.sun','name':'elevation'}) }}
{{ state_attr('sun.sun',*['elevation']) }}
{{ state_attr('sun.sun', **{'name':'elevation'}) }}
and similarly via the apply function, e.g.
{{ apply('ignored',state_attr,*['sun.sun','elevation']) }}
{{ apply('ignored',state_attr,'sun.sun', *['elevation']) }}
{{ apply('ignored',state_attr,'sun.sun', **{'name':'elevation'}) }}
So it seems to me, it should not be hard making these special functions also work with apply. What do you think?