Hi!
I want to use variable value from other variable with dynamically builded name
This is my case:
variables:
triger1_message: aaaa
triger2_message: bbbb
action:
- variables:
message: '{{ trigger.id ~ "_message" }}'
Currently message
will be triger1_message
or triger2_message
, but I want it to be aaaa
or bbbb
depending on which trigger was triggered…
Please help!
123
(Taras)
March 12, 2022, 4:07pm
2
It appears that what you want to do is to programmatically create the name of a variable using a template like this:
{{ trigger.id ~ "_message" }}
and then get the value of the resulting variable. So if the template produces triger1_message
you want to evaluate it and get its value aaaa
.
That would require the use of something like python’s eval
function but it doesn’t exist in Home Assistant’s implementation of Jinja2.
Yes, that is what I want to achive…
If this is not possible in way I tried, any other workaround exists?
123
(Taras)
March 12, 2022, 5:34pm
4
Define a dictionary and then lookup trigger.id
in the dictionary to find the matching value.
action:
- variables:
values:
triger1: 'aaaa'
triger2: 'bbbb'
triger3: 'cccc'
message: "{{ values.get(trigger.id, 'unknown') }}"
The following template means:
In the values
dictionary, find the key name provided by trigger.id
and return its value. If there is no matching key name, return unknown
.
{{ values.get(trigger.id, 'unknown') }}
1 Like
Thanks, it works this way!