Templates are the secret weapon of every advanced Home Assistant user. They let you create dynamic sensors, write smarter automations, send personalized notifications, and build dashboards that actually react to your home. Here's everything you need to go from copy-pasting YAML to writing your own templates with confidence.
Jump to a section
Templates use a language called Jinja2 to create dynamic values. Instead of hardcoding "turn on the lights at 7 PM," you can write logic that adapts to sunrise, who's home, or whether it's a workday.
Every template lives inside double curly braces. Here's one that shows the current temperature:
{{ states('sensor.living_room_temperature') }} °CThis pulls the live value of your temperature sensor. If it reads 21.5, the output is "21.5 °C".
{{ ... }} for outputting values
Use this to print a value. Most common in sensors and notifications.
{% ... %} for logic (if/for/set)
Use this for conditionals and loops. Nothing gets printed, it just controls flow.
{# ... #} for comments
Use this to leave notes for yourself. Comments are stripped from the output.
Before putting templates in your config, always test them in the Developer Tools template editor. It shows results in real time and catches errors before they break anything.
Count all lights that are on:
{{ states.light | selectattr('state', 'eq', 'on') | list | count }}Show a greeting based on time of day:
{% if now().hour < 12 %}Good morning{% elif now().hour < 18 %}Good afternoon{% else %}Good evening{% endif %}List all open doors:
{% for entity in states.binary_sensor if 'door' in entity.entity_id and entity.state == 'on' %}
- {{ entity.name }}
{% endfor %}Template sensors let you combine data from multiple entities into one clean value. They update automatically whenever the source entities change.
Add this to your configuration.yaml:
Multiply your energy usage by the current rate:
Shows how many minutes ago motion was last detected:
Lists everyone currently home:
Templates make your automations smarter. Use them in conditions, triggers, and actions to create logic that adapts instead of following rigid rules.
Only run the automation on weekdays when someone is home:
Lights get dimmer as the evening progresses:
Trigger when more than 3 windows are open (uses your template sensor):
Different scenes for different people:
Stop getting "Motion detected" notifications with zero context. Templates let you include exactly the information that matters.
Custom dashboard cards with dynamic content turn a static panel into a live overview of your home.
The built-in Markdown card supports full Jinja2:
Install Mushroom from HACS for the cleanest template cards:
Show cards only when relevant:
Bookmark this section. These are the filters, tests, and patterns you'll reach for over and over.
| float(0) Convert to number, default 0 if unavailable| int(0) Convert to integer| round(1) Round to 1 decimal place| default('fallback') Fallback value if result is empty or undefined| timestamp_custom Format a timestamp: ('%H:%M', true)| regex_search('pattern') Test if string matches a regex pattern| selectattr('key', 'eq', 'val') Filter a list of objects by attribute| map(attribute='name') Extract one field from each item in a list{{ now().strftime('%A') }} Day name (Monday, Tuesday...){{ now().weekday() }} 0 = Monday, 6 = Sunday{{ (as_timestamp(now()) - as_timestamp(states.sensor.x.last_changed)) | int }} Seconds since last state change{{ state_attr('sun.sun', 'next_rising') }} Next sunrise timeAlways use float(0) or int(0) with defaults
Without a default, an unavailable sensor will crash your template.
states() returns strings, not numbers
Always convert with | float or | int before doing math.
Check for 'unavailable' and 'unknown'
Entities can be in these states during restarts. Filter them out in loops.
Whitespace matters in YAML multi-line templates
Use > for folded text (joins lines) or | for literal blocks (keeps newlines). Add a minus sign (>- or |-) to strip trailing newlines.
Templates use the Jinja2 language to create dynamic values. Instead of hardcoding a number or text, you write a small expression that calculates the value on the fly. For example, a template sensor can show how many lights are on, or a notification template can include the current temperature. Templates work in automations, scripts, sensors, Lovelace cards, and almost anywhere you see a text field in YAML.
Go to Developer Tools in the sidebar, then click the Template tab. You get a live editor where you can write Jinja2 code and see the result immediately. It shows all available states and attributes, making it the fastest way to experiment.
The states function returns the main state of an entity as a string. The state_attr function returns a specific attribute, like brightness, battery level, or friendly_name. Use states for the primary value and state_attr when you need extra details.
Yes. Custom cards like Mushroom Template Card, custom:button-card, and the built-in Markdown card all support Jinja2 templates. You can show dynamic text, change icons based on state, and build cards that adapt to your home in real time.
Templates return "unavailable" when an entity they reference does not exist or is itself unavailable. Always add a default filter or wrap your template in an if/else check. For example, states('sensor.something') | default(0) ensures you get 0 instead of an error.
Add a template sensor in your configuration.yaml under the template: key. Define a name, a state template, and optionally a unit and device class. After saving, restart Home Assistant or reload template entities from Developer Tools. Check the examples above for five ready-to-use sensors.
Templates let you get the most out of Home Assistant. If you're migrating from Google Home, Alexa, or another platform, our free scan checks your current devices and shows you what's possible.