There are functions/filters to extract entities out of devices, areas and labels. But why is there no function to extract all entities out of a target? Someone please add a target_entities
function/filter.
Sure, most often you just pass the entire target directly to an action. But sometimes you may want to inspect the entities and do different things depending on states/attributes. For example different actions depending on whether lights within the target are all on, all off, or a mixed state.
Yes, obviously this already can be accomplished manually. But that is prone to errors, and if you wanted to do it in for example in a blueprint, you may end up with a lot of duplicate code if needing this function in several different places.
For anyone running into this topic in the future through googling, in case no-one on the HA team decides to add this to templating, here is a Jinja macro for you:
{%- macro target_entities(target, domain='[a-z_]+') -%} [ {%- for type, ids in target | items -%}
{%- set ids = ids is list and ids or ids is string and [ids] or [] %}{% for id in
(ids | map(type.removesuffix('_id') + '_entities') | sum(start=[]) if type != 'entity_id' else ids)
if id is match(domain + '[.]') -%} "{{ id }}", {%- endfor %}{% endfor -%} ] {%- endmacro -%}
Example usage:
{%- set entities = target_entities(target, 'lights') | from_json | unique | list -%}
As always there are caveats. If you do not add this to your custom_templates
, you will need to add it everywhere it is used – each template (even within the same automation) is its own silo. Also the result of a macro will always be a string, so you need to pass it through from_json
to get a list. Finally, to keep the macro short, it does not filter out any duplicates, so you may or may not want to do that yourself (using the unique
filter, as in example).