WTH is there not a target_entities function/filter?

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).

This would be a pretty easy add, not sure if it would be allowed though. Maybe I’ll attempt to push it through next week on break

1 Like

Nice. One additional note though… The blueprint target selector supports device and entity filters, but if for example using an entity filter only requires one entity within to match in order to return a device/area/label.

If sending the output of such a filtered target selector into a target_entities function, one may end up with many more entities than one would expect. Ideally a target_entities function would also support filters using the exact same syntax as a target selector does.

But then again, you have the same issue anywhere you plug the output of a target selector directly into an automation action. It may match many more entities than one had originally expected…

Yes, I know the limitations behind the selector, I created a template a couple of years ago that handles all cases. It’s somewhere on the forums.

EDIT: Here it is, it handled all target selector cases when I created it. It likely needs updating for floors and labels