Help converting a jinja template ( that includes an if statement ) to template sensor (value_template:)

Hi Guys,

A little help on the following would be most welcome.

I have successfully used the Developer Tools to craft a jinja template as follows:

{% if (states('sensor.6c_ct2_watts') | float - states('sensor.6c_ct1_watts') | float) * (-1) | float < 0 %}
     {% set actual_usage = {
       "watts": states('sensor.6c_ct2_watts'),
       "unit": "watts"
     } %}
{% else %}
     {% set actual_usage = {
       "watts": (states('sensor.6c_ct2_watts') | float - states('sensor.6c_ct1_watts') | float) * (-1),
       "unit": "watts"
     } %}
{% endif %}

Actual Usage > {{actual_usage.watts}}

This evaluate the if statement correctly and returns the value I am expecting.

My attempts to convert this to a Value Template Sensor has so far been unsuccessful.

Inside my sensors.yaml I have tried (amongst many variations) the following:

- platform: template
  sensors:
    6c_dn_current_watts:
      value_template: >
        {% if (states('sensor.6c_ct2_watts') | float - states('sensor.6c_ct1_watts') | float) * (-1) | float < 0 %}
          "{{states('sensor.6c_ct2_watts')}}"
        {% else %}
          "{{states('sensor.6c_ct2_watts') | float - states('sensor.6c_ct1_watts') | float) * (-1)}}"
        {% endif %}
      friendly_name: "DN House Total Watts"
      unit_of_measurement: "W"  

Visual Studio throws no errors but when I run the “Check Config” validation I get the following:

Configuration invalid

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['6c_dn_current_watts']['value_template']. Got '{% if (states(\'sensor.6c_ct2_watts\') | float - states(\'sensor.6c_ct1_watts\') | float) * (-1) | float < 0 %}\n "{{states(\'sensor.6c_ct2_watts\')}}"\n{% else %}\n "{{states(\'sensor.6c_ct2_watts\') | float - states(\'sensor.6c_ct1_watts\') | float) * (-1)}}"\n{% endif %}\n'. (See ?, line ?).

I just can not seem to get my syntax correct. Hoping someone can help

Thanks

There is a missing ( or a ) too much.

- platform: template
  sensors:
    6c_dn_current_watts:
      value_template: >
        {% if (states('sensor.6c_ct2_watts') | float - states('sensor.6c_ct1_watts') | float) * (-1) | float < 0 %}
          "{{states('sensor.6c_ct2_watts')}}"
        {% else %}
          "{{(states('sensor.6c_ct2_watts') | float - states('sensor.6c_ct1_watts') | float) * (-1)}}"
        {% endif %}
      friendly_name: "DN House Total Watts"
      unit_of_measurement: "W"  

Should work.

The issue is in the else part. you had {{ states... when it should be {{ (states...

Total awesome - that worked. Thanks for the quick response, nice work. :grinning:

Cheers