Iterate attribute to get list of entity_ids

Hi, I can template this ok:

{% for sonos in states.media_player.kitchen.attributes.sonos_group %}
  {{ sonos }}
{% endfor %}

if gives:

  media_player.kitchen

  media_player.kitchen_2

  media_player.deck

When I try to use it in an automation it fails with Error loading /config/configuration.yaml: while scanning for the next token found character ‘%’ that cannot start any token

- alias: 'kitchen_vol_down'
  trigger:
    platform: state
    entity_id: binary_sensor.kitchen_vol_down
    from: 'off'
    to: 'on'
  action:
    service: media_player.volume_down
    entity_id:
    data_template: >
    {% for sonos in states.media_player.kitchen.attributes.sonos_group %}
       ' {{sonos }}'
    {% endfor %}

I have tried all sorts of options and searched the web for hours. Welcome some advice please.
Regards David

1 Like

What does this report when you paste it into the Template Editor?

{{ state_attr('media_player.kitchen', 'sonos_group') }}

Does it look something like this?

['media_player.kitchen', 'media_player.kitchen_2', 'media_player.deck']

If not, post the result.

Hi, thankyou you for your help.
Yes it gives exactly what you suggest

['media_player.kitchen', 'media_player.kitchen_2', 'media_player.deck']

not sure how to now use that?

try line this:

action:
  service: media_player.volume_down
  data_template: 
    entity_id: "{{ state_attr('media_player.kitchen', 'sonos_group') }}"
action:
  service: media_player.volume_down
  data_template: 
    entity_id: "{{ state_attr('media_player.kitchen', 'sonos_group') | join(', ') }}"

This is a python list:

['media_player.kitchen', 'media_player.kitchen_2', 'media_player.deck']

whose YAML equivalent is this:

- media_player.kitchen
- media_player.kitchen_2
- media_player.deck

That appears to be acceptable for use with entity_id except that the result of any template is always a string value. That means the python list gets converted to a string; those square-brackets lose their special meaning (indicating they delimit a python list). Now seen as a string to entity_id, those square brackets become invalid characters.

The addition of the join filter converts the python list to a string and places commas between each of the list’s items:

media_player.kitchen, media_player.kitchen_2, media_player.deck

That’s an acceptable value for entity_id.

1 Like

Fantastic - thank you so much for all your help and clear explanation.
It really helps me learn.
This is a great forum - Thank You.
Cheers David

1 Like