Template


The template integration allows creating entities which derive their values from other data. This is done by specifying templates for properties of an entity, like the name or the state.

Sensors and binary (on/off) sensors are covered on this page. For other types, please see the specific pages:

Sensor and binary sensor template entities are defined in YAML directly under the template: key. You can define multiple configuration blocks as a list. Each block defines sensors and/or binary sensor entities and can contain an optional update trigger.

For old sensor/binary sensor configuration format, see below.

State-based template sensors

Template entities will by default update as soon as any of the referenced data in the template updates.

For example, you can have a template that takes the averages of two sensors. Home Assistant will update your template sensor as soon as either source sensor updates.

template:
  - sensor:
      - name: "Average temperature"
        unit_of_measurement: "°C"
        state: >
          {% set bedroom = states('sensor.bedroom_temperature') | float %}
          {% set kitchen = states('sensor.kitchen_temperature') | float %}

          {{ ((bedroom + kitchen) / 2) | round(1) }}

Trigger-based template sensors

If you want more control over when an entity updates, you can define a trigger. Triggers follow the same format and work exactly the same as triggers in automations. This feature is a great way to create entities based on webhook data (example), or update entities based on a schedule.

Whenever the trigger fires, all related entities will re-render and it will have access to the trigger data in the templates.

Trigger-based entities do not automatically update when states referenced in the templates change. This functionality can be added back by defining a state trigger for each entity that you want to trigger updates.

# Example configuration entry
template:
  - trigger:
      - platform: time_pattern
        # This will update every night
        hours: 0
        minutes: 0
    sensor:
      # Keep track how many days have past since a date
      - name: Not smoking
        state: '{{ ( ( as_timestamp(now()) - as_timestamp(strptime("06.07.2018", "%d.%m.%Y")) ) / 86400 ) | round }}'
        unit_of_measurement: "Days"

Configuration Variables

trigger list (Optional)

Define an automation trigger to update the entities. Optional. If omitted will update based on referenced entities. See trigger documentation.

unique_id string (Optional)

The unique ID for this config block. This will be prefixed to all unique IDs of all entities in this block.

sensor map Required

List of sensors

state template Required

Defines a template to get the state of the sensor.

unit_of_measurement string (Optional, default: None)

Defines the units of measurement of the sensor, if any. This will also influence the graphical presentation in the history visualization as a continuous value. Sensors with missing unit_of_measurement are showing as discrete values.

binary_sensor map Required

List of binary sensors

state template Required

The sensor is on if the template evaluates as True, yes, on, enable or a positive number. Any other value will render it as off. The actual appearance in the frontend (Open/Closed, Detected/Clear etc) depends on the sensor’s device_class value

delay_on time (Optional)

The amount of time (ie 0:00:05) the template state must be met before this sensor will switch to on. This can also be a template.

delay_off time (Optional)

The amount of time the template state must be not met before this sensor will switch to off. This can also be a template.

auto_off time (Optional)

Requires a trigger. After how much time the entity should turn off after it rendered ‘on’.

[both sensor and binary_sensor entities] map (Optional)

Fields that can be used above for both sensors and binary sensors.

name template (Optional)

Defines a template to get the name of the sensor.

unique_id string (Optional)

An ID that uniquely identifies this sensor. Will be combined with the unique ID of the configuration block if available. This allows changing the name, icon and entity_id from the web interface.

icon template (Optional)

Defines a template for the icon of the sensor.

picture template (Optional)

Defines a template for the entity picture of the sensor.

attributes map (Optional)

Defines templates for attributes of the sensor.

attribute: template template Required

The attribute and corresponding template.

availability template (Optional, default: true)

Defines a template to get the available state of the component. If the template returns true, the device is available. If the template returns any other value, the device will be unavailable. If not configured, the component will always be available.

device_class device_class (Optional, default: None)

Sets the class of the device, changing the device state and icon that is displayed on the UI (see below). It does not set the unit_of_measurement.

The above configuration variables describe a configuration section. The template integration allows defining multiple sections.

# Example configuration.yaml entry with two sections
template:
  # Define state-based template entities
  - sensor:
      ...
    binary_sensor:
      ...

  # Define trigger-based template entities
  - trigger:
      ...
    sensor:
      ...
    binary_sensor:
      ...

Rate limiting updates

When there are entities present in the template and no triggers are defined, the template will be re-rendered when one of the entities changes states. To avoid this taking up too many resources in Home Assistant, automatic rate limiting will be automatically applied if too many states are observed.

Define a trigger to avoid a rate limit and get more control over entity updates.

When states is used in a template by itself to iterate all states on the system, the template is re-rendered each time any state changed event happens if any part of the state is accessed. When merely counting states, the template is only re-rendered when a state is added or removed from the system. On busy systems with many entities or hundreds of thousands state changed events per day, templates may re-render more than desirable.

In the below example, re-renders are limited to once per minute because we iterate over all available entities:

template:
  - binary_sensor:
      - name: "Has Unavailable States"
        state: "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"

In the below example, re-renders are limited to once per second because we iterate over all entities in a single domain (sensor):

template:
  - binary_sensor:
      - name: "Has Unavailable States"
        state: "{{ states.sensor | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"

If the template accesses every state on the system, a rate limit of one update per minute is applied. If the template accesses all states under a specific domain, a rate limit of one update per second is applied. If the template only accesses specific states, receives update events for specifically referenced entities, or the homeassistant.update_entity service is used, no rate limit is applied.

Considerations

Startup

If you are using the state of a platform that might not be available during startup, the Template Sensor may get an unknown state. To avoid this, use is_state() function in your template. For example, you would replace {{ states.cover.source.state == 'open' }} with this equivalent that returns true/false and never gives an unknown result:

{{ is_state('switch.source', 'on') }}

Examples

In this section, you find some real-life examples of how to use this sensor.

Storing webhook information

Template entities can be triggered using any automation trigger, including webhook triggers. Use a trigger-based template entity to store this information in template entities.

template:
  - trigger:
      - platform: webhook
        webhook_id: my-super-secret-webhook-id
    sensor:
      - name: "Webhook Temperature"
        state: "{{ trigger.json.temperature }}"
        unit_of_measurement: °C

      - name: "Webhook Humidity"
        state: "{{ trigger.json.humidity }}"
        unit_of_measurement: %

    binary_sensor:
      - name: "Motion"
        state: "{{ trigger.json.motion }}"
        device_class: motion

You can test this trigger entity with the following CURL command:

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"temperature": 5, "humidity": 34, "motion": true}' \
  http://homeassistant.local:8123/api/webhook/my-super-secret-webhook-id

Sun Angle

This example shows the sun angle in the frontend.

template:
  - sensor:
      - name: Sun Angle
        unit_of_measurement: "°"
        state: "{{ '%+.1f'|format(state_attr('sun.sun', 'elevation')) }}"

Renaming Sensor Output

If you don’t like the wording of a sensor output, then the Template Sensor can help too. Let’s rename the output of the Sun component as a simple example:

template:
  - sensor:
      - name: "Sun State"
        state: >
          {% if is_state('sun.sun', 'above_horizon') %}
            up
          {% else %}
            down
          {% endif %}

Multiline Example With an if Test

This example shows a multiple line template with an if test. It looks at a sensing switch and shows on/off in the frontend.

template:
  - sensor:
      - name: "Kettle"
        state: >
          {% if is_state('switch.kettle', 'off') %}
            off
          {% elif state_attr('switch.kettle', 'kwh')|float < 1000 %}
            standby
          {% elif is_state('switch.kettle', 'on') %}
            on
          {% else %}
            failed
          {% endif %}

Change The Unit of Measurement

With a Template Sensor, it’s easy to convert given values into others if the unit of measurement doesn’t fit your needs.

template:
  - sensor:
      - name: "Transmission Down Speed"
        unit_of_measurement: "kB/s"
        state: "{{ states('sensor.transmission_down_speed')|float * 1024 }}"

      - name: "Transmission Up Speed"
        unit_of_measurement: "kB/s"
        state: "{{ states('sensor.transmission_up_speed')|float * 1024 }}"

Washing Machine Running

This example creates a washing machine “load running” sensor by monitoring an energy meter connected to the washer. During the washer’s operation, the energy meter will fluctuate wildly, hitting zero frequently even before the load is finished. By utilizing delay_off, we can have this sensor only turn off if there has been no washer activity for 5 minutes.

# Determine when the washing machine has a load running.
template:
  - binary_sensor:
      - name: "Washing Machine"
        delay_off:
          minutes: 5
        state: >
          {{ states('sensor.washing_machine_power')|float > 0 }}

Is Anyone Home

This example is determining if anyone is home based on the combination of device tracking and motion sensors. It’s extremely useful if you have kids/baby sitter/grand parents who might still be in your house that aren’t represented by a trackable device in Home Assistant. This is providing a composite of Wi-Fi based device tracking and Z-Wave multisensor presence sensors.

template:
  - binary_sensor:
      - name: People home
        state: >
          {{ is_state('device_tracker.sean', 'home')
             or is_state('device_tracker.susan', 'home')
             or is_state('binary_sensor.office_124', 'on')
             or is_state('binary_sensor.hallway_134', 'on')
             or is_state('binary_sensor.living_room_139', 'on')
             or is_state('binary_sensor.porch_ms6_1_129', 'on')
             or is_state('binary_sensor.family_room_144', 'on') }}

Device Tracker sensor with Latitude and Longitude Attributes

This example shows how to combine a non-GPS (e.g., NMAP) and GPS device tracker while still including latitude and longitude attributes

template:
  - binary_sensor:
      - name: My Device
        state: >
          {{ is_state('device_tracker.my_device_nmap', 'home') or is_state('device_tracker.my_device_gps', 'home') }
        device_class: "presence"
        attributes:
          latitude: >
            {% if is_state('device_tracker.my_device_nmap', 'home') %}
              {{ state_attr('zone.home', 'latitude') }}
            {% else %}
              {{ state_attr('device_tracker.my_device_gps', 'latitude') }}
            {% endif %}
          longitude: >
            {% if is_state('device_tracker.my_device_nmap', 'home') %}
              {{ state_attr('zone.home', 'longitude') }}
            {% else %}
              {{ state_attr('device_tracker.my_device_gps', 'longitude') }}
            {% endif %}

Change the icon when a state changes

This example demonstrates how to use template to change the icon as it’s state changes. This icon is referencing it’s own state.

template:
  - binary_sensor:
      - name: Sun Up
        state: >
          {{ is_state("sun.sun", "above_horizon") }}
        icon: >
          {% if is_state("binary_sensor.sun_up", "on") %}
            mdi:weather-sunset-up
          {% else %}
            mdi:weather-sunset-down
          {% endif %}

Legacy binary sensor configuration format

This format still works but is no longer recommended. Use modern configuration.

This format is configured as a platform for the binary_sensor integration and not directly under the template integration.

# Example configuration.yaml entry
binary_sensor:
  - platform: template
    sensors:
      sun_up:
        friendly_name: "Sun is up"
        value_template: {{ state_attr('sun.sun', 'elevation') > 0 }}

Configuration Variables

sensors map Required

List of your sensors.

sensor_name map Required

The slug of the sensor.

friendly_name string (Optional)

Name to use in the frontend.

unique_id string (Optional)

An ID that uniquely identifies this binary sensor. Set this to a unique value to allow customization through the UI.

device_class device_class (Optional, default: None)

Sets the class of the device, changing the device state and icon that is displayed on the frontend.

value_template template Required

The sensor is on if the template evaluates as True and off otherwise. The actual appearance in the frontend (Open/Closed, Detected/Clear etc) depends on the sensor’s device_class value

availability_template template (Optional, default: true)

Defines a template to get the available state of the component. If the template returns true, the device is available. If the template returns any other value, the device will be unavailable. If availability_template is not configured, the component will always be available.

icon_template template (Optional)

Defines a template for the icon of the sensor.

entity_picture_template template (Optional)

Defines a template for the entity picture of the sensor.

attribute_templates map (Optional)

Defines templates for attributes of the sensor.

attribute: template template Required

The attribute and corresponding template.

delay_on time (Optional)

The amount of time the template state must be met before this sensor will switch to on. This can also be a template.

delay_off time (Optional)

The amount of time the template state must be not met before this sensor will switch to off. This can also be a template.

Legacy Sensor configuration format

This format still works but is no longer recommended. Use modern configuration.

This format is configured as a platform for the sensor integration and not directly under the template integration.

# Example configuration.yaml entry
sensor:
  - platform: template
    sensors:
      solar_angle:
        friendly_name: "Sun angle"
        unit_of_measurement: "degrees"
        value_template: "{{ state_attr('sun.sun', 'elevation') }}"

      sunrise:
        value_template: "{{ state_attr('sun.sun', 'next_rising') }}"

Configuration Variables

sensors map Required

Map of your sensors.

friendly_name string (Optional)

Name to use in the frontend.

friendly_name_template template (Optional)

Defines a template for the name to be used in the frontend (this overrides friendly_name).

unique_id string (Optional)

An ID that uniquely identifies this sensor. Set this to a unique value to allow customization through the UI.

unit_of_measurement string (Optional, default: None)

Defines the units of measurement of the sensor, if any. This will also influence the graphical presentation in the history visualization as a continuous value. Sensors with missing unit_of_measurement are showing as discrete values.

value_template template Required

Defines a template to get the state of the sensor.

icon_template template (Optional)

Defines a template for the icon of the sensor.

entity_picture_template template (Optional)

Defines a template for the entity picture of the sensor.

attribute_templates map (Optional)

Defines templates for attributes of the sensor.

attribute: template template Required

The attribute and corresponding template.

availability_template template (Optional, default: true)

Defines a template to get the available state of the component. If the template returns true, the device is available. If the template returns any other value, the device will be unavailable. If availability_template is not configured, the component will always be available.

device_class device_class (Optional, default: None)

Sets the class of the device, changing the device state and icon that is displayed on the UI (see below). It does not set the unit_of_measurement.