Sorting sensors by area in template

what is the right way of managing the sorting by areas in templating in home assistant?

This is how I do it (not optimal probably):

        {% set ns = namespace(entity_and_area=[]) -%}
        {%- for entity in states.sensor  -%}
          {%- set entity_id = entity.entity_id -%}
          {%- set area = area_name(entity.entity_id) -%}
          {%- if area is not none -%}
            {%- set entity_and_area = ({'entity_id':entity_id,'area':area}) -%}
            {%- set ns.entity_and_area = ns.entity_and_area + [entity_and_area] -%}
          {%- endif -%}
        {%- endfor -%}
        {%- set sorted_list = (ns.entity_and_area) | sort(attribute=sort) -%}
        {{ sorted_list | map(attribute='entity_id') | list }}

Next time do not post a code as a picture.

See this, matches the output you want

{%- for area in areas() | map('area_name') | sort %}
  {%- for e in area_entities(area) | expand | selectattr('attributes.device_class', 'eq', 'temperature') | selectattr('attributes.state_class', 'eq', 'measurement') %}
{{ area }} - {{ e.name }}: {{ e.state }}{{ e.attributes.unit_of_measurement }}
  {%- endfor %}
{%- endfor %}

EDIT: Forgot you can use the state_with_unit property too

{%- for area in areas() | map('area_name') | sort %}
  {%- for e in area_entities(area) | expand | selectattr('attributes.device_class', 'eq', 'temperature') | selectattr('attributes.state_class', 'eq', 'measurement') %}
{{ area }} - {{ e.name }}: {{ e.state_with_unit }}
  {%- endfor %}
{%- endfor %}
1 Like

apologies. i chose to post as a screenshot so that i can also show the unordered output, as I thought it clarifies the problem. in the future, i will add the code as well.

I am a bit confused with the dash of the {%- in your code, after and before {%
Thats how new I am :slight_smile:
thank you

the - removes leading or trailing whitespace.

1 Like

You are absolutely right about providing a picture since it describes a format in which you want to get data. But a code is also needed; use a “preformatted code” option or triple “`” (a button located right below “ESC”).

1 Like

Learning a lot and fast. Thanks again. Your code works excellently, exactly as i needed, in developer tools/template.

but i am greedy, i immediately wanted to carry over the info to the markdown card.

i am missing an architectural point, am i not?

thanks in advance,

the frontend is less forgiving than the template editor.

{%- for area in areas() | map('area_name') | sort %}
  {%- for e in area_entities(area) | expand | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'temperature') %}
{{ area }} - {{ e.name }}: {{ e.state_with_unit }}
  {%- endfor %}
{%- endfor %}
1 Like

cant thank you enough.

I feel less bad that the difference is non-trivial.