How to use trigger.entity_id in a data_template

Hello everybody

In an automation I want to set a variable with this action:

  - service: var.set
    data_template:
      entity_id: "var.consigne_{{trigger.entity_id.split('.')[1].split('_')[0]}}"
      value: "{{ states ('input_number.consigne_eco_bureau') }}"

The value of ‘{{trigger.entity_id.split(’.’)[1].split(’’)[0]’ is ‘bureau’. How to parametrize the value ?
Something like :
value: "{{ states ('input_number.consigne_eco
’trigger.entity_id.split(’.’)[1].split(’_’)[0]) }}"

Thanks for your help

1 Like
value: "{{ states ('input_number.consigne_eco_' + trigger.entity_id.split('.')[1].split('_')[0]) }}"

If your automation uses a State Trigger then the Trigger State Object will contain:

trigger.to_state.object_id

which can be used instead of:

trigger.entity_id.split('.')[1]

You can use that to create a local variable in the automation’s action. The variable can be referenced by both templates.

  action:
  - variables:
      chambre: "{{ trigger.to_state.object_id.split('_')[0] }}"
  - service: var.set
    data:
      entity_id: "var.consigne_{{chambre}}"
      value: "{{ states('input_number.consigne_eco_' ~ chambre) }}"

Thanks a lot !
I’ve learned the ‘variables’ inside an automation. very useful. Makes automation clearer.

BTW when you concatenate too strings what should I use ‘+’ and/or ‘~’ ?
You use ‘~’ and CentralCommand in the previous answer uses ‘+’.

Thanks for the lesson

  • The tilde (~) concatenates strings. Even if you provide numbers, they will be handled as strings.
  • The plus sign (+) adds numbers. If there are no numbers, only strings, they will be concatenated. However, an error will occur if there is a mix of numbers and strings.

Notice the difference in how the two operators, ~ and +, behave:

Screenshot from 2021-01-10 15-49-57

If I add the template {{ 56 + 'cat' }} it results in an error because I am instructing it to add a number to a string.

Screenshot from 2021-01-10 15-54-17