Template sensor : attribute value always null

I’ve been going round in circles with this one.

I’m trying to create a template sensor that has two attributes -
current_aqi - a rounded value of another sensor
current_description - a text value based on the value of current_aqi

I’ve studied the template docs, various posts, and even existing template sensors I have in place.

- name: "Internal AQI"
      unique_id: internal_aqi
      state: OK
      attributes:
        current_aqi: >
          {% set aqi = states('sensor.average_internal_air_quality') | float %}
          {{ (aqi) | round(0, default=0) }}
        current_description: >
          {% if aqi <= 50 %} Excellent
          {% elif aqi >= 51 and aqi <=100 %} Good
          {% elif aqi >= 101 and aqi <= 150 %} Lightly Polluted
          {% elif aqi >= 151 and aqi <= 200 %} Moderately Polluted
          {% elif aqi >= 201 and aqi <= 250 %} Heavily Polluted
          {% elif aqi >= 251 and aqi <= 350 %} Severely Polluted
          {% else %} Extremely Polluted
          {% endif %}

When I test this in Developer Tools > Template, the attributes are returned correctly

- name: "Internal AQI"
      unique_id: internal_aqi
      state: OK
      attributes:
        current_aqi: >
          
          59
        current_description: >
           Good

But whenever I put it into templates.yaml, reload the templates, then check it under states, current_description is always returned as null

current_aqi: 60
current_description: null
friendly_name: Internal AQI

I’ve tried encasing the text values with double, and single quotes; no change. I’ve even tested reducing it to just 2 outcomes and replacing the text values with numeric, still it returns null.

I’m guessing I’ve missed something simple but just cannot see it.

Any help or guidance appreciated :slight_smile:

As far as I know, variables are local to the specific attribute.

Try and set the variable aqi in the current_description attribute too.

Every day is a school day! Thank you @zenzay42 , worked perfectly :smile:

1 Like

Glad I could help!

And yes, always something new to learn about HA… it’s hard to pin down a moving target :slight_smile:

Note that you compare aqi which is the floating point value before being rounded. A value of 50.5 will cause the current_description to be set to Extremely Polluted (the default choice when nothing matches). You should remove the first part of your elif conditions and only keep the part after the and:

{% if aqi <= 50 %} Excellent
{% elif aqi <= 100 %} Good
[…]
1 Like

Can you post the final working code, please? Just to clarify.