I’m trying to implement an automation where in the condition I do a somewhat elaborate operation to collect information from the trigger state, use that compiled information as part of the condition, and then use the same data in the action.
First of all, how would I go about passing a variable from the condition phase down to the action? Apparently, if I simply assign it to a local variable, it’s not available later (I assume not the same execution scope). I tried things like assigning it to an attribute of this
, but that doesn’t work either.
My other issue is with the data collection itself. What I’m trying to do is iterate over an array of objects among the attributes of the from
and to
state, and collect all that was changed in a certain way.
Most conveniently I would go about this using the stream/lambda function paradigm, but as far as I could tell, the latter is not available in the template language (which would be required to form the non-trivial condition for the change detection).
The next approach would be of course to declare an empty array, iterate over the observed collection, and put any found changes into that array. The issue is that apparently, an object declared outside of the loop can’t be accessed from within for some weird reason. In the dev tools template editor I get SecurityError: unsafe
for the line in the loop’s body; and in an automation condition, I get Encountered unknown tag 'changes'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'
.
{%
set from_state = [
{ "name": "a", "value": "xx" },
{ "name": "b", "value": "y" },
{ "name": "c", "value": "z" },
]
-%}
{%
set to_state = [
{ "name": "a", "value": "x" },
{ "name": "b", "value": "yy" },
{ "name": "c", "value": "z" },
]
-%}
{% set changes = [] -%}
{% for item in to_state -%}
{% if item.value != from_state[loop.index - 1].value -%}
{% changes.append(item) -%}
{% endif -%}
{% endfor -%}