Data_template for entity_id - inconsistent error

Hi there I am getting inconsistent behavior for a templated automation that I cannot explain:

This one is working correctly

 alias: Screens Power
  trigger:
    platform: state
    entity_id: input_select.screen_selector
  action:
  service: script.turn_on
  data_template:
    entity_id: >
      {% if is_state("input_select.screen_selector", "TV") %}script.tv_toggle_power 
      {%-elif is_state("input_select.screen_selector", "PJ") %}
        script.pj_toggle_power
     {%-elif is_state("input_select.screen_selector", "off") %}
       script.tv_toggle_power, script.pj_toggle_power_off
     {% else %}
       none
     {% endif %}

but when I change the automation to check for input_boolean state

 alias: Screens Power
 trigger:
 platform: state
  entity_id: input_select.screen_selector
 action:
  service: script.turn_on
   data_template:
     entity_id: >
      {% if is_state("input_select.screen_selector", "TV") %}script.tv_toggle_power 
      {%-elif is_state("input_select.screen_selector", "PJ") %}
        script.pj_toggle_power
      {%-elif is_state ("input_select.screen_selector", "off") and is_state ("input_boolean.pj_power_state", "on") -%} script.pj_toggle_power_off
      {%-elif (is_state ("input_select.screen_selector", "off")) and (is_state ("input_boolean.tv_power_state", "on")) -%} script.tv_toggle_power
      {% else %}
        none
      {% endif %}

Hass throws an error for the second template but not the first one.
Both templates are working correctly in templates testing panel for all conditions, and the error hass throws is

script.tv_toggle_power is an invalid entity id for dictionary value @ data['entity_id']. Got 'script.tv_toggle_power\n\n\n\n\n\n\n#  #   script.tv_toggle_power, script.pj_toggle_power_off #'

The error changes depending on the state of the input select and condition … any help to figure out what is causing this error?

the formatting is horrible… also, you’re stipping leading whitespace sometimes and not others {%- vs {%. Also, not sure you parenthesis are correct… could you try it with cleaned up code? Like:

     {% if is_state("input_select.screen_selector", "TV") %}
        script.tv_toggle_power
     {% elif is_state("input_select.screen_selector", "PJ") %}
        script.pj_toggle_power
     {% elif (is_state ("input_select.screen_selector", "off") and is_state ("input_boolean.pj_power_state", "on")) -%} 
        script.pj_toggle_power_off
     {% elif (is_state ("input_select.screen_selector", "off") and is_state ("input_boolean.tv_power_state", "on")) -%} 
        script.tv_toggle_power
     {% else %}
        none
     {% endif %}
2 Likes

Thank you, the leading whitespace stripping was the mistake.