Loop through multiple device_class’s

Hi.
I have contact sensors configured as door and window. I use the following code to loop through the door class


{% for state in states.binary_sensor
| selectattr('attributes.device_class', 'defined') 
| selectattr('attributes.device_class', 'eq','door')  %}
| selectattr('attributes.device_class', 'eq','window')
{% if state.state == 'off' %}
{{ state.entity_id }} = {{ state.state }}
{% endif %}
{% endfor %}

The output is this


The code only shows the doors and not the windows. I also tried to add the window line as ‘or’ statement but that doesn’t work either
I want to show items either configured as door or window in this loop. Can it be done?

Try this:

{%- for state in states.binary_sensor
| selectattr('attributes.device_class', 'defined') 
| selectattr('attributes.device_class', 'in',['door','window'])  %}
{%- if state.state == 'off' %}
{{ state.entity_id }} = {{ state.state }}
{%- endif %}
{%- endfor %}

This is taking the list of binary sensors and filtering only the door sensor, then using the result of this (only the door sensors) and trying to select only the windows sensors from there, but there’s no Windows sensors, as you have previously removed any binary sensor that are not door sensors.

By the way, this is a simpler way to get the entity_id of all door and windows sensors that are off. If you really want to have the output as you’ve done, then create your for loop from this and you might even save a few cycles in your CPU:

{{ states.binary_sensor
| selectattr('attributes.device_class', 'defined') 
| selectattr('attributes.device_class', 'in',['door','window']) 
| selectattr('state', 'eq', 'off')
| map(attribute='entity_id')
| list
}}

Yes this works. I tried something similar and using ‘search’ and ‘find’ instead of ‘in’, in combination with [‘door’,’window’] but that didn’t work. So I was close Thanks for your super fast reply and help. Still trying to figure out all the possible commands I can use.

1 Like