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

10 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