Template filtering on an attribute that is not on all entities within a domain

Hello!

I’ve trying to use the template in this post in order to get a count of devices on a particular UniFi Network SSID.

Template
{% 
    set dev_count = states.device_tracker | 
    selectattr('state', 'eq', 'home') |
    selectattr('attributes.essid', 'eq', "guest_ssid") |
    list |
    count
%}
{% if dev_count == 1 %}
    {{dev_count}} device connected
{% else %}
    {{dev_count}} devices connected
{% endif %}

However, it doesn’t work consistently because not all entities within the device_tracker domain have an essid attribute (devices connected with Ethernet, the companion app etc.) thus causing an error:

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'essid'

Sometimes the Mushroom template card is able to render this before the error prevents it, but that’s rare, and usually the template’s raw text is printed instead.

I wrote a (particularly inefficient) template designed to filter on all entities that contained the essid attribute, and then count the amount of entities which contained the relevant SSID string. But then I discovered the issues around Jinja not allowing for list.append() for security reasons alongside the fact that variables were lost outside of for loops etc.

An even more broken template
{% set devices = [] %}
{% for entity in states.device_tracker %}
  {% if 'essid' in entity['attributes'].keys() %}
    {% if 'guest_ssid' in entity['attributes'].values() %}
      {% set devices = devices + [entity] %}
    {% endif %}
  {% endif %}
{% endfor %}

{% set dev_count = devices | list | count  %} 

{% if dev_count == 1 %}
  {{dev_count}} guest device connected
{% else %}
  {{dev_count}} guest devices connected
{% endif %}

Overall, I’d like to know if there’s a way to use selectattr, but ignore any attribute not found errors.

Thank you!

 {% set hamedia = entities
            | rejectattr('state','in',('idle','off','unavailable','paused'))
            | selectattr("attributes.app_name", 'defined')
            | selectattr('attributes.app_name','in',('Home Assistant Media Player','Home Assistant Lovelace Player','Default Media Receiver'))
            | map(attribute='entity_id') | list | length %}

Sorted it!

There’s another test for selectattr: defined.

{{ 
  states.device_tracker | 
  selectattr('attributes.essid','defined') | 
  selectattr('attributes.essid','eq','[SSID]') |
  list | count
}}