Can't get if else statements to work

Hi,

I have recently started to use Home Assistant. I have some automations that turn my light switches on and off. I have now created a input_boolean named “guests” that I want to be able to switch on and off depending on if I have guests sleeping in our guest room. In that case I don’t want the light switch in the guest room turn on in the morning.
My config right now is:

- id: '1544829850937'
  alias: Lamps morning light up
  trigger:
  - at: 05:00
    platform: time
  condition: []
  action:
  - alias: ''
    data:
      entity_id: switch.kontor, switch.vardagsrum_2, switch.vardagsrum2_2, switch.tvattrum, switch.julgranen, switch.gastrum_2
    service: switch.turn_on

I have tried the following but it won’t work:

action:
  - service: homeassistant.turn_on
    data:
      entity_id: >-
        {% if is_state('input_boolean.guests', 'on') %}
          - switch.kontor
          - switch.vardagsrum_2
          - switch.vardagsrum2_2
          - switch.tvattrum
          - switch.julgranen
        {% else %}
          - switch.kontor
          - switch.vardagsrum_2
          - switch.vardagsrum2_2
          - switch.julgranen
          - switch.tvattrum
          - switch.gastrum_2
        {% endif %}

Can someone please give me some advice?

Regards
Patrik

Can you please format your code properly?

I’m sorry for that. I have fixed it now.

There are a couple of problems. First, when using a template for data items, you need to change data: to data_template:. Next, a template only returns a single string. So although it looks like you’re creating a list, you’re actually creating a single string that contains a bunch of dashes, which is not a valid value for entity_id. You need to use commas.

Try this:

action:
  - service: homeassistant.turn_on
    data_template:
      entity_id: >
        switch.kontor,
        switch.vardagsrum_2,
        switch.vardagsrum2_2,
        switch.tvattrum,
        switch.julgranen
        {% if is_state('input_boolean.guests', 'off') %}
          , switch.gastrum_2
        {% endif %}
3 Likes

Thank you so much! It works (with a change to switch.turn_on instead of homeassistant.turn_on)

I didn’t know templates was only returning a single string. This made everything much clearer for me.

Thanks!

Either should work. Some people only use homeassistant.xxx when they can.