Template wizards, is there a more elegant way to do this?

I want to be able to go through a list of entities provided by an integration and match one of them based on a case-insensitive comparison of an attribute, and then select a different value from the entity.

Here’s an example:

{# Pretend this is a variable that will be handed to this script by
   something external, i.e., a converstation assistant. #}
{% set incoming_variable_from_ai = 'Kitchen speaker' -%}

{%- set ids = integration_entities('music_assistant') | list -%}
{%- set names = ids 
  | map('state_attr', 'friendly_name') 
  | map('lower') 
  | list -%}
{%- set index = names.index(incoming_variable_from_ai | lower) -%}

{# I'm writing the entity_id here, but this is where I would
   get a different attribute #}
{{ ids[index] }} 

I feel like there is a simpler way to accomplish this that I’m just not seeing. This also works, but if only there were a filter that selectattr accepted that could do a case-insensitive comparison. I didn’t see one while googling. Did I miss something?

{# An alternate method which loops over the state objects in order
   to compare an attribute case-insensitively, but then select 
   different attribute #}
{%- for ps in integration_entities('music_assistant') | expand -%}
  {%- if ps.attributes.friendly_name | lower == incoming_variable_from_ai | lower -%}
    {{ ps.entity_id }}
    {%- break -%}
  {%- endif -%}
{%- endfor -%}
{{ integration_entities('music_assistant') | expand | selectattr('name', 'search', incoming_variable_from_ai, ignorecase=True) | map(attribute='entity_id') | list }}

I knew it! There had to be a nice, elegant way to do it.

Thanks!

no idea if it works :rofl:

EDIT: It does

Small change, first instead of list:

{{ integration_entities('music_assistant') 
  | expand 
  | selectattr('name', 'search', incoming_variable_from_ai, ignorecase=True)
  | map(attribute='entity_id') 
  | first }}

well yeah, I was just showing you how to get them.

If you want to get the first one, you’d end it with | first | default to avoid errors

1 Like