Conditional in Value_Template

Hi guys. I’ve been slowly learning how to get around Home Assistant but I am finally stuck with this bit of code

      is_exporting:
        unit_of_measurement: 'Index'
        # 1 = importing, 2 = top up HWS, 3 = Exporting and Diverting to HWS, 4 = Exporting, 0 = undefined error
        value_template: >-
          {% if (((states('sensor.solar_power_a')|float) > 0.0) and (states('solar_power_b')|float > 0.0)) %} 
            1
          {% else %}
            0
          {% endif %}

Everything validates under developer tools but the state of the entity always shows a value of unavailable. If I replace the right hand side of the and with 1>0 it evaluates correctly. solar_power_b = 0.0 at this time.

This is the beginnings of a if/elif/elif/elif/else statement but I cut it back to basics for troubleshooting.
Any help would be much appreciated.

You need to assign a default to your float filters… Updating Templates with the new default values in 2021.10.x

TL:DR
{% if states('sensor.solar_power_a')|float(0) > 0.0 and states('solar_power_b')|float(0) > 0.0 %}

1 Like

Thank you so much. That fixed it.
This what I came up with

      is_exporting:
        unit_of_measurement: 'Index'
        # 1 = top up HWS, 2 = importing, 3 = Exporting and Diverting to HWS, 4 = Exporting, 0 = undefined error
        value_template: >-
          {% if (((states('sensor.solar_power_a')|float(0)) > 0.0) and (states('solar_power_b')|float(0) > 0.0)) %} 
            1
          {% elif (states('sensor.solar_power_a')|float(0) > 0.0  and (states('solar_power_b')|float(0)) <= 0.0) %}
            2
          {% elif (states('sensor.solar_power_b')|float(0) > 10.0  and (states('solar_power_c')|float(0)) > 10.0) %}     
            3
          {% elif (states('sensor.solar_power_b')|float(0) <= 10.0 and (states('solar_power_c')|float(0)) > 10.0) %}     
            4
          {% else %}
            0
          {% endif %}

Now I just have to make sure my logic is correct!

If you wish, you can use Jinja2 variables to make the template less verbose. You can also place the values on the same line as the statement to reduce whitespace (although that’s just a choice of style).

        value_template: >-
          {% set a = states('sensor.solar_power_a') | float(0) %}
          {% set b = states('sensor.solar_power_b') | float(0) %}
          {% set c = states('sensor.solar_power_c') | float(0) %}
          {% if a > 0 and b > 0 %} 1
          {% elif a > 0  and b <= 0 %} 2
          {% elif b > 10 and c > 10 %} 3
          {% elif b <= 10 and c > 10 %} 4
          {% else %} 0
          {% endif %}
1 Like

Thanks, I did see you could use variables with set but I have just been adding one feature at a time. The templating language is so different to normal programming I’ve been struggling with it a bit.