Variables in template to have different messages

Hello,
I wrote a simple automation which turn off lights when nobody is in house AND sun is above horizon and it works:

- alias: "Turn off lights"
  trigger:
    - platform: state
      entity_id: XXXXXXX
      from: 'home'
      to: 'not_home'
  action:
     - service: light.turn_off
       data_template:
         entity_id: >-
           {% if is_state('sun.sun', 'above_horizon') %}
           group.all_lights
           {% else %}
           light.yeelight_rgb_XXXXXXX
           {% endif %}
     - delay: 00:00:02
     - service: notify.telegram
       data:
         message: 'all the lights have been turned off'

I added these lines of code but it doesn’t works:

- alias: "Turn off all lights"
  trigger:
    - platform: state
      entity_id: XXXXXXXXX
      from: 'home'
      to: 'not_home'
  action:
     - service: light.turn_off
       data_template:
         entity_id: >-
           {% if is_state('sun.sun', 'above_horizon') %}
           group.all_lights
           {% set msg_txt="'all the lights have been turned off" %}
           {% else %}
           light.yeelight_rgb_XXXXXX
           {% set msg_txt="Turn off only some lights" %}
           {% endif %}
     - delay: 00:00:02
     - service: notify.telegram
       data_template:
         message: "{{ msg_txt }}"

There is no global template context. Each template has its own context. So when you set a variable named msg_txt in the first template, when the second template is evaluated, that variable no long exists.

You basically need to repeat the if-else statement. E.g.:

- alias: "Turn off all lights"
  trigger:
    - platform: state
      entity_id: XXXXXXXXX
      from: 'home'
      to: 'not_home'
  action:
    - service: light.turn_off
      data_template:
        entity_id: >
          {% if is_state('sun.sun', 'above_horizon') %}
            group.all_lights
          {% else %}
            light.yeelight_rgb_XXXXXX
          {% endif %}
    - delay: 00:00:02
    - service: notify.telegram
      data_template:
        message: >
          {{ 'All' if is_state('sun.sun', 'above_horizon') else
             'Only some of' }} the lights have been turned off
1 Like

I would like to set a text message based on the actions taken.
Sould I add an “and” condition in your working example? Because in your example the message is set independently if the lights are off, but only if “the sun is above the horizon”