Template Syntax for icon change depending on numerical sensor level

Hi all,
I’m trying to figure out the right syntax for a template sensor for which the icon changes depending on the value of another sensor.

For my central heating custom button card, I defined a template sensor for the CH Pump which changes icon based on the power consumption of the pump. If power consumption of the pump is below 10 Watt, the pump is assumed to be off, so the icon should change to the off state.

Current Syntax:

  - name: "Tmpl_CH_Pump_Status"
    state: " {{ states['sensor.ch_pump_power'].state }} "
    unit_of_measurement: "W"
    icon: >
      {% if states.sensor.ch_pump_power.state > 10 %}
        mdi:toggle-switch-outline
      {% elif states.sensor.ch_pump_power.state <= 10 %}
        mdi:toggle-switch-off-outline
      {% else %}
        mdi:exclamation-thick
      {% endif %}

I tried a lot of different variations, like

{% if states['sensor.ch_pump_power'].state > 10 %}

and

{% if states['sensor.ch_pump_power'].state | float > 10 %}

and

{% set power = states('sensor.ch_pump_power') | float %}
{% if power > 10 %}

But no suc6, the icon is always on.

Any ideas what’s wrong.
Thx
PPee

This should do it:

  - name: "Tmpl_CH_Pump_Status"
    state: "{{ states('sensor.ch_pump_power') }}"
    unit_of_measurement: "W"
    icon: >
      {% if states('sensor.ch_pump_power')|float(0) > 10 %}
        mdi:toggle-switch-outline
      {% elif states('sensor.ch_pump_power')|float(0) <= 10 %}
        mdi:toggle-switch-off-outline
      {% else %}
        mdi:exclamation-thick
      {% endif %}
1 Like

That’ll never go unavailable because you’re using a default of zero. It will always show off in that case.

      {% set power = states('sensor.ch_pump_power')|float(none) %}
      {% if power is not none %}
        mdi:toggle-switch{{ '-off' if power <= 10 else '' }}-outline
      {% else %}
        mdi:exclamation-thick
      {% endif %}
2 Likes

But the default is only used if the state isn’t able to be converted to a floating point number.

Right, which will put it in the off icon when it should be hitting the ! Icon. Because it fails to convert and places the result as zero, which will hit the less than or equal to 10.

Ah. Got it. :+1:

Thx, Petro and Tom,
Both solution seem to work.
Thx again for your help !!