Template to get entities with specific state out of a media group

Hi there,
I’m struggling a bit with an automation where I want to set a volume to all speakers with “on” state.

I have to create a template which gives me all speakers with “on” state, so I can set the volume on them.
First I’ve created a speaker group:

media_player:
  - platform: group
    name: Lautsprecher
    entities:
      - media_player.player1
      - media_player.player2
      - media_player.player3
      - media_player.player4
      - media_player.player5
      - media_player.player6
      - media_player.player7

According to the documentation (Working with Groups) I tried to create the following template:

{% for entity_id in expand('media_player.lautsprecher') %}
  {% if is_state(entity_id.entity_id, 'on') %}
    {{- entity_id.entity_id }}
  {% endif %}
{% endfor %}

As a result I get media_player.lautsprecher, although it’s not in the group and other media players have the “on” state.

For me it seems as if the expand() function doesn’t work as stated in the documentation, but I have too less experience with templates to be sure. Can anybody help me to figure out what’s wrong here?

Many thanks in advance!

expand doesn’t work on media_player groups or light groups, you have to extract the entity_ids from the attribute. You also don’t need a for loop for this, you can just use jinja filters to reduce your list and output what you want with map.

{{ expand(state_attr('media_player.lautsprecher', 'entity_id')) | selectattr('state','eq','on') | map(attribute='entity_id') | list }}
2 Likes

Thank you very much, this works like a charm!

Is there any documentation which groups are supported and maybe why/why not?

Only group is supported. No other domains. It doesn’t explicitly say this in the docs but all the examples only show the group domain being used. I guess it’s implied.

i.e.

group.xyz is the group domain

media_player.xyz is the media_player domain

therefore it expand will only expand group.xyz.

Light groups now work with expand! Wow, something changed… I wasn’t able to do this before:

{{ expand('light.kitchen_lights') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list | length }}
1 Like