Template to get all persons' trackers in zone

Hi, I’m trying to determine which persons are in a zone (when a automation is running) by checking the zone of their device_trackers. Now I was already able to print something when the device tracker is in the zone. Now I only want to determine whether at least one device is in a zone and then print the persons name. Unfortunately you cannot break out of the loop in jinja as far as I can tell.

{% for state in states.person -%}
{{ state.name }}
  {% for attr in state.attributes['device_trackers'] -%}
    {% if states(attr) == 'home' %} Home {% endif %}
  {%- endfor %}
{%- endfor %}

Is there another way to do the check? There is a length filter, but that doesn’t work with the for-each loop and I haven’t found a way to count the length of a “sublist”. If it were in python it would look something like this:

for state in states.person:
  if any(for attr in state.attributes['device_trackers'] if states(attr) == 'home'):
    print(state.name)

You should have a home zone entity. The state of that entity will be a count of the number of people that are home.

Unfortunately I want to list who is in that zone and that is something the zone doesn’t provide.

:thinking:
People in the family = group.awesome_people

How many people are at home

     state: >
       {%- set people = expand('group.awesome_people') %}
       {{ people | selectattr('state', 'in', ['home', 'on'] ) | list | count }}

Who’s in the house

    state: > 
         {%- set people = expand('group.awesome_people') | selectattr('state', 'eq', 'home') | map(attribute='name') | list %}
         {%- set company = expand('group.awesome_people') | selectattr('state', 'eq', 'on') | map(attribute='name') | list %}
         {%- set people = people + company %}
         {{ people }}

ScreenShot_20230805160423

Zone has an attribute of persons which is a list of people in that zone.

Try this in the Template Developer Tool

{%- for person in state_attr("zone.home", "persons") %}
{{ person }}
{%- endfor %}

Thanks with selectattr I was able to actually solve this:

{{ states.person | selectattr('state', 'in', ['home'] ) | map(attribute='name') | join(', ') }}
2 Likes

Am I correct in my understanding that this doesn’t really return a “person”-object?

You are correct. It returns the entity_id. Not the object.