#Filter states list by "contains attribute"

1 messages · Page 1 of 1 (latest)

vital canyon
#

I have template (simplified):

states.media_player|selectattr('state', '==', 'playing')|selectattr('volume_level', '>', '0')|list

But it gives error UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'volume_level' because one of playing media players doesn't report volume level.
Is there a good way to reject those? Like |rejectattr('volume_level', 'eq', Undefined)?

#

(because this thing rejects all, actually)

#

The best i could go with is

{% set p = states.media_player|selectattr('state', '==', 'playing')|map(attribute='entity_id')|list %}
{% set f = namespace(e=[]) %}
{% for i in p %}
 {% if state_attr(i, "volume_level") %}
  {% set f.e = f.e + [i] %}
 {% endif %}
{% endfor %}
{{ f.e }}

It's ugly AF, and could be replaced with one filter, if it's there.

#

But i can't find one...

silver panther
#

I would try
| selectattr('attributes.volume_level', 'defined')

#

But if you adjust
|selectattr('volume_level', '>', '0')
to
|selectattr('attributes.volume_level', '>', '0')
it will complain about '>' not being supported between instances of 'float' and 'str'

vital canyon
vital canyon
silver panther
#

If you want to remove muted media players, i would try the following
|rejectattr('attributes.is_volume_muted', 'true')
to get around the string/float problem.

#

But that might not work with every media player. It depends on the available attributes,