Unfortunately there’s no way to do that template using selectattr
. At least not that I’ve figured out, maybe someone has a trick, if so would love to hear it.
The problem is that you can only use tests in select
and selectattr
filters and Jinja does not have a built-in test for contains
. Home Assistant has extended Jinja with regular expression support as you noted but regex_search
and regex_match
are defined as filters not tests. This means they cannot be used in a select
or selectattr
statement even though it makes sense to do so. I created a bug on it but looks like its an enhancement. Meant to look into it but haven’t gotten around to it.
Without those being tests you’ll have to use a for loop to get this done. Something like this should do the trick:
{% set ns = namespace(update_sensors=[],on_sensors=(states.binary_sensor | selectattr('state', 'eq', 'on') | list)) %}
{% for s in ns.on_sensors %}
{% if "update" in s.name | lower or "update" in s.entity_id %}
{% set ns.update_sensors = ns.update_sensors + [s] %}
{% endif %}
{% endfor %}
{{ ns.update_sensors | map(attribute="entity_id") | unique | join(", ") }}
EDIT: Since I got a notification that @brodykenrick liked this I should probably update it to not lead people on the wrong path. This comment here:
Home Assistant has extended Jinja with regular expression support as you noted but regex_search
and regex_match
are defined as filters not tests.
Is not true anymore since search and match were added as tests
So nowadays this is a better way to solve this without involving a for loop:
{% set update_name = states.binary_sensor | selectattr('state', 'eq', 'on')
| selectattr('name', 'search', '(?i)update') | list %}
{% set update_id = states.binary_sensor | selectattr('state', 'eq', 'on')
| selectattr('entity_id', 'search', 'update') | list %}
{{ (update_name + update_id) | map(attribute='entity_id') | unique | join(", ") }}
Although that or
still requires multiple concatenated templates instead of a single one (either the name OR the ID contains update). If you only care about entities that have update
in their ID then you can simplify this to one template:
{{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('entity_id', 'search', 'update')
| map(attribute='entity_id') | unique | join(", ") }}