PSA: Templates and YAML. Distinguishing Jinja from YAML

Templates are indicated by lines that start and end with {% %} or {{ }}. Everything else is yaml. The language contained inside {% %} and {{ }} is Jinja, it is not yaml.

Examples of a template:

{% set x = 4 %}
{{ x }}

Example of a template inside yaml

some_field: >
  {% set x = 4 %}
  {{ x }}

explanation:

some_field: > # THIS IS YAML
  {% set x = 4 %}  #THIS IS JINJA
  {{ x }} # THIS IS JINJA

The character > in the some_field line is yaml. This mean the next set of indented lines are part of this field. It is not a jinja or template indicator. It is not related to templates at all. It only tells the yaml that the next few lines are text that should be included in the some_field field.

some_field: "{{ states('sensor.xyz') }}"
\          /^\                        /^----- closing quote, more yaml
 \________/ | \______________________/
   |        |                       |
yaml      open quote, yaml         Jinja

A template and yaml combined into a single line. The quotes tell the yaml that this line is a string and everything between the quotes is part of some_field field.


Jinja documentation
https://jinja.palletsprojects.com/en/latest/templates/

On top of what is built into jinja in the link above, home assistant has added extra methods documented here:

If you’re trying to use the trigger information, that’s documented here

12 Likes

This should be part of the Templating documentation. :+1:

One other thing worth mentioning is that YAML is processed first followed by Jinja2. Not knowing the order of processing, and the boundaries between YAML and Jinja2, is what has led some people to “template YAML” where they attempt to use a Jinja2 template to generate complete YAML statements.

5 Likes

One other thing which confused me when first starting with Home Assistant templates:

You give the example here with the > character:

some_field: >
  {% set x = 4 %}
  {{ x }}

But I kept seeing examples of people using various syntax:

Apparently it relates to line folding in the YAML language. If the code that follows is split onto multiple lines, then the character used determines whether or not the new line characters are replaced with spaces or not (i.e. if the code is folded back together on a single line). Including the - character after either > or | determines what happens with the final line break in the code block.

The behaviour is nicely summarized here:

Is this described somewhere in the Home Assistant documentation? Or not, because it’s really part of learning YAML ?

The fact that they are for multi-line strings is noted a couple places in the docs, but the specific functions of each symbol are not explained because:

  1. As you said, it’s really a part of YAML not unique to Home Assistant.
  2. In most cases where they would be used in HA, it doesn’t matter much which one you use.

Example mention:

From Building Templates