Template sensor, if state_attr

I have a template sensor with different attributes, look like this

I would like to use the attributes in a template sensor, using if but I cant get it to work propperly and I cant understand way.

This code returns value B, but in my mind i want it to return value A. What am I doing wrong?

{% if state_attr('sensor.template_countdown', 'stadning') == '1' %}
A
{% else %}
B
{%- endif %}

I would like it to return value A when the attribute is 1

While states are always strings, attributes can be other data type such as floats, lists, or (as in your example) integers. Comparisons in templates are specific to data type, so ‘1’ is not the same as 1.

2 Likes

Try this:

{% if state_attr('sensor.template_countdown', 'stadning') | float(0) == 1 %}
  A
{% else %}
  B
{% endif %}
{{ iif(is_state_attr('sensor.template_countdown', 'stadning',  1), 'A', 'B') }}
3 Likes

Okey, didn’t know about that but makes sens. Thank for the information!

That worked, thanks!

There’s no need for the float filter because the value of stadning is an integer. You simply need to compare it with an integer value 1, not a string '1'. That’s why your original template failed because you compared an integer to a string.

1 Like

OK, now I see the difference, and that works perfectly. Thanks!