#Template variable in the automation trigger and action

1 messages · Page 1 of 1 (latest)

next marlin
#

I have an automation that fires on various events, one of them is when one entity values becomes greater-or-equal to another entity:

  - trigger: template
    value_template: |-
      {{ states('sensor.my_sensor')|int >= states('input_number.my_threshold')|int }}

But because this automation also fires on various other events that all perform the same job (when main switch is turned off, when HA starts, etc), I have to run the if statement in the actions block, checking again if {{ states('sensor.my_sensor')|int >= states('input_number.my_threshold')|int }}

How, and is there a way (trigger variables, variables maybe?) that would allow me to define the variable in the automation, like so:

# Create global variable
my_var: {{ states('sensor.my_sensor')|int >= states('input_number.my_threshold')|int }}

# Use it in the trigger
triggers:
  - trigger: template
    value_template: '{{ my_var }}'
  # other triggers

actions:
  - if:
      - condition: template
        value_template: '{{ my_var }}'
    then:
      ....

The objective is to not repeat myself with the same code blocks.

solid cipher
#

Hello @next marlin,
Add a trigger_id: in that trigger and test for it below, or add a variable:in the trigger itself to set something you can decide on.

#

Then you know if that was the trigger that happened.

next marlin
#

Trigger id does not help since the same if/else sequence must go through, regardless of the trigger. I would still need to check for comparison in case trigger is not the one with selected id

solid cipher
#

I assume you are setting that my_var as a trigger_variable so the trigger can see it.

#

Also ```yaml

  • if:
    • condition: template
      value_template: '{{ my_var }}'
#

only needs to be

  - if: '{{ my_var }}'

In the bottom one because it's a boolean answer.
Not sure if you can shorten it in the trigger, probably not.

next marlin
#

you are right most likely, but I still need to duplicate the code, which was my only point trying to avoid.

I will keep it for now as it is.

regal orchid
#

trigger_variables only allow Limited Templates, which excludes the states() function, so that's not an option. If you need it more "global" create a Template binary sensor and trigger/condition off its state.