Toggle entities from a scene by reading the entity list from the scene

Hi,

I need help with a script to toggle entities within a scene
I can read the entity with this command from the scene:

{{state_attr("scene.weihnachtsbeleuchtung_innen_ein", "entity_id")[3]}}
The output is: the name of the entity (e.g. switch.ikea_weihnachtsbaum)

But I get an error, if I try to toggle the entity:

service: switch.toggle
data: {}
target:
  entity_id: {{state_attr("scene.weihnachtsbeleuchtung_innen_ein", "entity_id")[3]}}

can someone help to toggle/switch on/off an entity from the arry above?
Spartacus

Single line templates need to be enclosed in quotes.

service: switch.toggle
data: {}
target:
  entity_id: '{{ state_attr("scene.weihnachtsbeleuchtung_innen_ein", "entity_id")[3] }}'

Rule 1:

thanks, I found it myselve, but is it also possible to loop this for all entities with in the array?

like:

service: switch.toggle
data: {}
target:
  '{% for entity in state_attr("scene.weihnachtsbeleuchtung_innen_ein", "entity_id") %}'
    entity_id: '{{ (entity) }}'
  '{% endfor %}'

seems to that there is also something wrong with it, I found no solution

repeat for each

  - repeat:
      for_each: "{{ state_attr('scene.weihnachtsbeleuchtung_innen_ein', 'entity_id') }}"
      sequence:
        - service: switch.toggle
          target:
            entity_id: "{{ repeat.item }}"

Hi,
cool! many thanks for it! This happens if you only think in one direction

Spartacus

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic is resolved. This helps other users find answers to similar questions.

For more information, refer to guideline 21 in the FAQ.

…I will do this directley, but let me ask one last question:

{% set total=0 %}
  {% for entity in state_attr("scene.weihnachtsbeleuchtung_innen_ein", "entity_id") %}
  {% if states(entity)=="on" %}
  {% set total = total + 1 %}
  {% endif %}
  {% endfor %}
{{total}}

I am using this code in a makrdown card and the issue is, that the variable “total” is not calculated. Seems to be that it is only locally available within the “for-loop”. How can this be solved?
Thanks and have a nice day!

ok, I have it:

{% set total = namespace(value=0) %}
  {% for entity in state_attr("scene.weihnachtsbeleuchtung_innen_ein", "entity_id") %}
  {% if states(entity)=="on" %}
  {% set total.value = total.value + 1 %}
  {% endif %}
  {% endfor %}
{{total.value}}