Template with if's: failed to reload configuration - scanning for next token found character % that cannot start any token

I’m trying to write a very simple template in which I want to give an output depending on the value of a sensor (positive or negative).

I’m a newcomer and so far I’ve been able to write even simpler templates doing operations with sensors.
As soon as I include the if statement, I get the weirdest errors which I’m not able to interpret, not to say to fix!

the code works perfectly well in the Developer tools → Template Editor (as per below)

{% if states('sensor.sh_3em_linea_principale_total_power') | float(0) < 0.0 -%}
      state: {{ states('sensor.mpz_total_power_consumption') }}
    {%- else -%}
      state: {{ states('sensor.verso_giusto_power') }}
    {%- endif %}

returning:

Result type: string

state: 197.19

This template listens for the following state changed events:

* **Entity**: sensor.mpz_total_power_consumption
* **Entity**: sensor.sh_3em_linea_principale_total_power

After inserting the code in the template.yaml file, with the proper formatting, I can’t restart HA.

By proper formatting, from what the very little I understood, I get that the language is to be modified slightly because the template file is parsed as YAML. Instead, the {{…}}’s are parsed/evaluated as Jinja templates. The syntax in either cases is not very clear to me, didn’t find a place with a clear enough explanation for a neophyte.
The best I could find about adapting code from template editor to template.yaml was this (Important template rules). Any better and more complete suggestion?

One of the errors I get when trying to reload, related to the code block below, is the following:
Cannot quick reload all YAML configurations because the configuration is not valid: Error loading /config/configuration.yaml: while scanning for the next token found character ‘%’ that cannot start any token in “/config/templates.yaml”, line 71, column 6

The code is the following:

- sensor:
##------------
##  Total effective power
##     this template is working properly
  - name: MPz Total Power Consumption
    state: "{{ states('sensor.piano_1_power') | float(0) + states('sensor.piano_t_power') | float(0) + states('sensor.locale_t_power') | float(0) + states('sensor.loctecnenergia_power') | float(0) }}"
    unit_of_measurement: 'W'

##  Self consumption power
##      this template returns errors when saved into templates.yaml
  - name: MPz Selfconsumption
    {% if states('sensor.sh_3em_linea_principale_total_power') | float(0) < 0.0 | float(0) %}
      state: "{{ states('sensor.MPz_Total_Power_Consumption') | float(0) }}"
    {% else %}
      state: "{{ states('sensor.verso_giusto_power') | float(0) }}"
    {% endif %}

Line 71 is the following (in the above code):

    {% if states('sensor.sh_3em_linea_principale_total_power') | float(0) < 0.0 | float(0) %}

I’ve looked everywhere for help, both in this blog (for instance in this post) and elsewhere to no avail.

I’ve experimented with

  • rewriting the code from scratch several times
  • Indentations, spaces
  • “…”, ‘…’ before&after the {%…%}
  • much simpler code like the following (which again does work in the template editor and fails in the templates.yaml with the same error):
    {% if 1.0 < 0.0 %}
      state: "{{ 1.0 }}"
    {% else %}
      state: "{{ -1.0 }}"
    {% endif %}
  • I’ve tried to write the code both with Studio Code Server from inside HA and externally with xCode

With the former (Studio Code) I get errors inside Studio as well, more than one and that again I don’t understand, I provide both the code and a screenshot

##  Self Consumption power
##      
  - name: MPz Self Consumption
    {% if states('sensor.sh_3em_linea_principale_total_power') | float(0) < 0.0 | float(0) %}
      state: "{{ states('sensor.MPz_Total_Power_Consumption') | float(0) }}"
    {% else %}
      state: "{{ states('sensor.verso_giusto_power') | float(0) }}"
    {% endif %}
    unit_of_measurement: 'W'

which looks totally the same, and the followings are the errors shown:

My system is the following (working from a MacBook Pro 16" M1 Max):
Home Assistant 2023.10.3
Supervisor 2023.10.0
Operating System 11.0
Frontend 20231005.0 - latest
on a Raspberry Pi 4-64

Summarising… i’m lost and I thank you all in advance for any help.
Forgive any language and programming mistake, as I said, i’m a newby and I tried all the best myself for several days (and nights) :grinning_face_with_smiling_eyes:

You can only template the value of a key: value, not the key. So this:

{% if states('sensor.sh_3em_linea_principale_total_power') | float(0) < 0.0 -%}
      state: {{ states('sensor.mpz_total_power_consumption') }}
    {%- else -%}
      state: {{ states('sensor.verso_giusto_power') }}
    {%- endif %}

Should be:

state: >
  {% if states('sensor.sh_3em_linea_principale_total_power') | float(0) < 0.0 %}
    {{ states('sensor.mpz_total_power_consumption') }}
  {% else %}
    {{ states('sensor.verso_giusto_power') }}
  {% endif %}

The Template Editor only evaluates Jinja templates. It doesn’t evaluate anything else like the YAML included in your example. For the Jinja processor, state: is handled as a string and is not understood to be YAML syntax.

That’s a legitimate complaint because your example does in fact contain invalid YAML.

Your example attempts to generate YAML using Jinja. As tom_l explained, you can’t do that. Home Assistant processes all YAML first and then Jinja second. Therefore you can’t use Jinja to produce/control YAML.

Thank you both! You gave me a lot of precious and important hints over which to meditate (in addition to, and even more important than, the actual solution of the problem!)

If my understanding is correct, my main and silly mistake was that {{...}} and {%...%} are Jinja (which of course work in the template editor) but such a code has to be controlled by Yaml code in the template. If so, my mistake was that I started a line with Jinja with no Yaml to control it.

I have the feeling that I still do not correctly interpret Tom’s sentence:

You can only template the value of a key: value , not the key

Likely I do not grab the meaning of key, my proficiency of HA glossary is still very very poor. Am I correct in assuming that keys are Jinja statements so I can’t directly “template” them but they have to be controlled by Yaml command/statemens which extract the values from keys?

Again, thanks a lot!

Yes, that was the only thing I knew :wink:, that state: was going to be misinterpreted by Jinja template editor. I lazily left it there because it was going to be interpreted as a string, as you said, with no harm.
I thanked you already on the next post for the precious help, I learned a lot from your explanations.

See section 2.1.2: https://www.commonwl.org/user_guide/topics/yaml-guide.html#key-value-pairs

thanks again, was precisely looking for something similar