How to use variable in script template condition? works for values

Hello folks,

i use automation to dynamically change brightness level on Shelly Dimmer2. It would normally turn light on when off so i wanted to return to previous state, checking if it is actually turned on. Thus using more complex script to use same code for all dimmers.

What i can’t figure out is how to use template value in condition, something like
{{ is_state(’{{light_entity}}’, ‘on’)}} instead of fixed value {{ is_state(‘light.shellydimmer2’, ‘on’)}}
If i change to first option it always ends up false so my statement has to be wrong somehow.

Any advice?

script_setdimmerbrightness:
  alias: SetDimmerBrightness
  sequence:
  - if:
      condition: template
      value_template: >
        {{ is_state('light.shellydimmer2', 'on')}} 'this is where i want entity name sent to the script
    then:
      - service: light.turn_on
        data_template: 
          entity_id: >
            {{light_entity}}
          brightness: >
            {{custom_brightness}}
    else:
      - service: light.turn_on
        data_template: 
          entity_id: >
            {{light_entity}}
          brightness: >
            {{custom_brightness}}
      - delay:
          seconds: 1            
      - service: light.turn_off
        data_template: 
          entity_id: >
            {{light_entity}}     
  mode: queued

Just use the variable, you don’t need to nest a template within the template.

script_setdimmerbrightness:
  alias: SetDimmerBrightness
  sequence:
  - if:
      condition: template
      value_template: >
        {{ is_state(light_entity, 'on') }}
    then:
      - service: light.turn_on
        data_template: 
          entity_id: >
            {{light_entity}}
          brightness: >
            {{custom_brightness}}
    else:
      - service: light.turn_on
        data_template: 
          entity_id: >
            {{light_entity}}
          brightness: >
            {{custom_brightness}}
      - delay:
          seconds: 1            
      - service: light.turn_off
        data_template: 
          entity_id: >
            {{ light_entity }}     
  mode: queued
1 Like

Same functionality but without duplicating light.turn_on.

script_setdimmerbrightness:
  alias: SetDimmerBrightness
  sequence:
    - variables:
        light_initially_off: "{{ is_state(light_entity, 'off') }}"
    - service: light.turn_on
      target: 
        entity_id: '{{ light_entity }}'
      data:
        brightness: '{{ custom_brightness }}'
    - condition: template
      value_template: "{{ light_initially_off }}"
    - delay:
        seconds: 1            
    - service: light.turn_off
      target: 
        entity_id: '{{ light_entity }}'
  mode: queued
1 Like

Thanks both, brilliant code optimization. Works like charm :slight_smile:

1 Like