Where to use templates

Once you know what templates are, the next question is usually “where do I actually put one?”. You’ll reach for a template when you write a notification with live sensor values, trigger an automation based on the current state of your home, or build a dashboard number from several entities at once. Templates show up in a lot of places in Home Assistant, and this page walks through the most common ones so you can recognize each spot when you meet it.

You don’t need to memorize this. Come back when you’re building something and need to remember which field accepts a template.

Automation and script actions

Most actions accept templates for their data values. You can use them to compose messages, pick targets, or tailor behavior based on the current state of your home.

AutomationAutomations in Home Assistant allow you to automatically respond to things that happen in and around your home. [Learn more]
- alias: "Goodnight message"
  triggers:
    - trigger: time
      at: "23:00:00"
  actions:
    - action: notify.send_message
      target:
        entity_id: notify.my_device
      data:
        message: >
          Goodnight.
          {{ states('sensor.front_door') | capitalize }} front door, and
          {{ states.light | selectattr('state', 'eq', 'on') | list | count }}
          lights still on.
Result
Goodnight. Closed front door, and 3 lights still on.

Automation conditions

A Template condition lets an automation decide whether to continue based on any test you can write. The template needs to end up either True or False, and the automation only continues when the answer is True.

ConditionConditions check whether something is true at that moment, for example, whether a door is closed. You can use them in automations and scripts. If a condition is not met, the actions that come after it in the same sequence do not run. At the top level of an automation or script, this stops the automation or script. [Learn more]
conditions:
  - condition: template
    value_template: >
      {{ states('sensor.outdoor_temperature') | float(0) < 5 }}
Result
True (when the outdoor temperature is below 5°C)

Automation triggers

A template trigger reacts when the template changes from false to true. This lets you react to conditions that no single entity represents.

TriggerA trigger is the part of an automation that makes the automation start when something specific happens, for example, when the sun sets, a door opens, or a button is pressed. [Learn more]
triggers:
  - trigger: template
    value_template: >
      {{
        states('sensor.washing_machine_power') | float(0) < 5
        and states('sensor.washing_machine_power') | float(0) > 0
      }}
Result
True (fires when the washing machine power drops between 0 and 5 W)

Limited templates

A few fields only accept limited templates, such as trigger_variables and the enabled option of triggers, conditions, and other steps. A limited template can’t read the state of your home or the current time. For what limited templates can use, and which fields use limited templates, refer to Limited templates.

Template entities

The Template integration lets you create entitiesAn entity represents a sensor, actor, or function in Home Assistant. Entities are used to monitor physical properties or to control other entities. An entity is usually part of a device or a service. [Learn more] whose value is computed from other entities. Template sensorsSensors return information about a thing, for instance the level of water in a tank. [Learn more], binary sensors, switches, and more are defined entirely with templates.

AutomationAutomations in Home Assistant allow you to automatically respond to things that happen in and around your home. [Learn more]
template:
  - sensor:
      - name: "Lights on"
        state: >
          {{ states.light | selectattr('state', 'eq', 'on') | list | count }}
Result
5 (the sensor reports the number of lights currently on)

Notifications

The notify actions accept templates for the title, message, and often other fields. This is one of the most popular places to use templates, because it turns fixed notifications into personal, context-aware messages.

ActionAn action makes Home Assistant do something, for example, turn on a light, send a notification, or activate a scene. Automations and scripts run a list of actions. [Learn more]
- action: notify.send_message
  target:
    entity_id: notify.my_device
  data:
    title: "Door alert"
    message: >
      {{ trigger.to_state.name }} was opened at
      {{ now().strftime('%H:%M') }}.
Result
Front door was opened at 14:32.

REST and command-line sensors

The rest and command_line sensors use templates to pull values out of the raw response they receive. This is how you turn a JSON reply or a command’s output into a usable sensorSensors return information about a thing, for instance the level of water in a tank. [Learn more].

AutomationAutomations in Home Assistant allow you to automatically respond to things that happen in and around your home. [Learn more]
sensor:
  - platform: rest
    resource: https://api.example.com/weather
    name: "Outside humidity"
    value_template: "{{ value_json.current.humidity }}"
    unit_of_measurement: "%"
Result
72 (extracted from the JSON field current.humidity)

MQTT

The MQTT integration accepts templates for topics, payloads, and value extraction. Incoming payloads are often JSON, so a template extracts the field you need.

AutomationAutomations in Home Assistant allow you to automatically respond to things that happen in and around your home. [Learn more]
mqtt:
  sensor:
    - name: "Garden moisture"
      state_topic: "garden/sensor/moisture"
      value_template: "{{ value_json.moisture }}"
      unit_of_measurement: "%"
Result
45 (extracted from an MQTT payload like {"moisture": 45})

MQTT uses two kinds of templates. A value template transforms an incoming payload into an entity state or attribute. A command template turns an action into the outgoing payload that the device expects. Both get the usual value and value_json variables, plus three extras specific to MQTT:

  • entity_id: the entity ID that the template belongs to.
  • name: the friendly name of the entity.
  • this: the entity’s own state object (the same one you meet in template entities).

The MQTT integration documentation has the full list of where each template type applies and which fields on each entity support templating.

Processing incoming data

The REST, MQTT, and command-line examples above use two special variables that need a word of introduction: value and value_json. You will run into them anywhere Home Assistant pulls data from an outside source and hands it to a template for shaping.

When raw data comes in, the template that processes it has these extras available:

  • value holds the raw incoming data as text. It is always there.
  • value_json holds the same data parsed as JSON. It is only there when the data actually is valid JSON.

So when an MQTT payload arrives like this:

{ "state": "ON", "temperature": 21.9, "humidity": 54 }

You can reach the fields with dot notation:

TemplateA template is an automation definition that can include variables for the action or data from the trigger values. This allows automations to generate dynamic actions. [Learn more]
Temperature: {{ value_json.temperature }}
Humidity: {{ value_json.humidity }}
State: {{ value_json.state }}
Result
Temperature: 21.9
Humidity: 54
State: ON

Nested JSON

Real-world payloads often have nested structures. Use square brackets to reach deeper:

TemplateA template is an automation definition that can include variables for the action or data from the trigger values. This allows automations to generate dynamic actions. [Learn more]
{% set value_json = {
  "sensor": {"type": "air", "id": "12345"},
  "values": {"temp": 26.09, "hum": 56.73}
} %}
Sensor ID: {{ value_json['sensor']['id'] }}
Temperature: {{ value_json['values']['temp'] }}
Result
Sensor ID: 12345
Temperature: 26.09

For simple field names, you can also use dots, such as value_json.sensor.id. Use square brackets when a field name contains characters that dots don’t handle, like a dash or a space, or when it has the same name as a built-in function of a dictionary, such as values, items, keys, or get. For example, value_json.values returns the function instead of the field, so the template output is empty.

JSON arrays

If the data is a list, index into it with square brackets (starting at zero):

TemplateA template is an automation definition that can include variables for the action or data from the trigger values. This allows automations to generate dynamic actions. [Learn more]
{% set value_json = {"primes": [2, 3, 5, 7, 11, 13]} %}
First prime: {{ value_json.primes[0] }}
Third prime: {{ value_json.primes[2] }}
Result
First prime: 2
Third prime: 5

When the data is not JSON

If the incoming data is plain text or a number (say, from a command-line sensor that outputs 42.5), use value directly:

TemplateA template is an automation definition that can include variables for the action or data from the trigger values. This allows automations to generate dynamic actions. [Learn more]
{% set value = "42.5" %}
{{ value | float(0) + 1 }}
Result
43.5

Remember: value is always text, so convert with | float(0) or | int(0) before doing math.

Testing an incoming-data template

The template editor does not know what value_json or value would be in a real incoming payload, because there is no live payload at that moment. To test a template that uses these variables, define them yourself at the top with {% set %}:

TemplateA template is an automation definition that can include variables for the action or data from the trigger values. This allows automations to generate dynamic actions. [Learn more]
{% set value_json = {"name": "Outside",
                     "data": {"temp": "24C", "hum": "35%"}} %}
Humidity reading: {{ value_json.data.hum[:-1] }}%
Result
Humidity reading: 35%

This lets you work out the right template in the editor, then paste the finished version into your REST sensor, MQTT entity, or command-line sensor without needing the real device to send data.

Dashboards

Most dashboard cards don’t render templates. Two places do:

To show a calculated value on any other card, create a template sensor, and add that sensor to the card.

Not everywhere

Not every field accepts templates. As a rule:

  • Text, numbers, and lists in automation actions, conditions, triggers, and scripts can usually be templated.
  • Entity IDs and structural YAMLYAML is a human-readable data serialization language. It is used to store and transmit data in a structured format. In Home Assistant, YAML is used for configuration, for example in the configuration.yaml or automations.yaml files. [Learn more] keys usually cannot.
  • On dashboards, only the Markdown card and the Template visibility condition render templates.

If a template is not being evaluated, it is most likely in a field that does not support templating. The Debugging templates page has more tips.

Next steps

Now that you know where templates live, learn how to write them: