What the Heck is a Template and how can I use it?

What are Templates?

If you have look at any Home Assistant documentation, you should have noticed that most configuration is composed of key/value pairs like…

entity_id: switch.example

… where entity_id is the key and switch.example is the value.

At the most basic level, the Jinja Templates in Home Assistant are a way to dynamically calculate values. Templates allow us to retrieve data like the state of entities and process that data using logic, math, and other programming tools to make those values dynamic.

Where Should I use Templates?

Use them where they are supported. If you don’t know if they are supported in a particular location within your configuration the best thing to do it to check the documentation.
Integrations that are still configured in YAML usually have a section of their documentation labelled “Configuration Variables” [example]. The section consists of a list of the allowed configuration variable keys used by that integration and information about those variables. If templating is supported it will say “template” next to the variable’s key. If templates are not supported, it will say the data type that is expected such as string, float, integer, or list.

image

Additionally, the documentation is full of YAML configuration examples. A lot of effort has been made to include template examples where they are supported.

Where can I use Templates in the UI?

When Should I use Templates?

There are thousands of times when you might want to use a template.

  • When you need a value to change based on certain criteria. Example: When you turn it on, have a light’s change based on the time of day.
  • When you need to modify a value. Example: A sensor state that tells you the temperature difference between inside and outside.
  • When you want to make your automation or script more compact. Templates can often replace the logic of complex chains of conditions or a Choose action with a dozen options, in just a few lines.

Templating can be used to solve simple problems like the examples above or perform much more complicated computations.

How do I use Templates?

  1. a. Read “Building Templates” and the Jinja Documentation to get an idea of what tools are available.
    b. Read tutorials or watch videos .
  2. Think about a problem that you want to solve.
  3. Try to solve it with templates in the Template Tool . If you get stuck, do a search… if you can’t find an answer, start a new forum thread and ask for help.
  4. Implement the solution.

The Home Assistant Cookbook - Index

6 Likes