Template troubles. Confused by output

Trying to create a template that sets an icon colour based on power wall charge state.

It should show anything less than 40 as red, 40-69 amber 70-00 green and 100 blue. But for some reason I’m missing, when the charge hits 100%, the colour output is red.

Code below, what have I missed?

 {% set state=states('sensor.powerwall_charge') %}
  {% if state <'40' %}
  red
  {% elif state=='100' %}
  blue
  {% elif state>='40' and state<='69' %}
  amber
  {% else %}
  green
  {% endif %}

{{ states('sensor.powerwall_charge') }}

Worth me adding that when I remove the blue section, it still turns red at 100, when I would expect to to be green as it’s >69.

The statements are checked in order, and you are comparing strings when you need to compare numbers. Also your indentation is not good. Try this:

 {% set state = states('sensor.powerwall_charge')|float(0) %}
 {% if state < 40 %}
   red
 {% elif 40 <= state <= 69 %}
   amber
 {% elif state == 100 %}
   blue
 {% else %}
   green
 {% endif %}
1 Like

Thanks, that’s got it working perfectly now.

For future reference, here’s a way to get the same result but with a dictionary:

{% set x = states('sensor.powerwall_charge') | float(0) %}
{{ {x < 40: 'red', 40 <= x <= 69: 'amber', x == 100: 'blue'}.get(true, 'green') }}
1 Like

Great thanks, my mistakes were obvious once pointed out, but certainly had me scratching my head for a while.