Converting a working template in Jinja2 to YAML for a sensor

  • As Edwin says, please format code correctly for the forum. See here.
  • Your general templating style (referring to states) is not best practice. Read this, in particular the warning box at the bottom of the States section.
  • I’ve never seen anyone use the lt test rather than the < operator like that. Where did you get that from? Was it AI?
  • You don’t need to use YAML, you can create this as a Template Sensor Helper in the UI. Just use a state template of:
{% set fronius = states('sensor.fronius_primo_power_ac')|int(0) %}
{% set phase2 = states('sensor.mainspower_ct2_watts')|int(0) %}
{% if fronius < phase2 %}
{{ phase2 - fronius }}
{% else %}
{{ phase2 * -1 }}
{% endif %}

Like this:

If you needed to use YAML for some reason, like the availability template, it’d look like this (properly formatted, and under the template: heading):

template:
  - sensor:
      - name: "Net Power Total"
        unit_of_measurement: "W"
        state: >
          {% set fronius = states('sensor.fronius_primo_power_ac')|int(0) %}
          {% set phase2 = states('sensor.mainspower_ct2_watts')|int(0) %}
          {% if fronius < phase2 %}
            {{ phase2 - fronius }}
          {% else %}
            {{ phase2 * -1 }}
          {% endif %}
        device_class: power