AboutPostsTalksOpen sourceProjectsPodcastsVideosToolsResumeContact

Mastering Complex Templates in Home Assistant: A Comprehensive Guide

Unlock the Full Potential of Automation with Custom Templates

Photo by Johannes Plenio on Unsplash.
Photo by Johannes Plenio on Unsplash.

Introduction

**Why Create Custom Templates?**

Home Assistant is already pretty smart. It can turn on lights, adjust your thermostat, and even play your favorite music. But imagine if you could teach it to do even more, exactly the way you want it to. That's where templates come in.

Templates are like secret codes that tell Home Assistant what to do in different situations. They can make your home super efficient, comfortable, and personalized.

In this guide, we'll walk you through creating your own powerful templates. We'll break down the process step-by-step, so even if you're new to Home Assistant, you'll be creating complex automations in no time.

Ready to supercharge your smart home? Let's dive in!

Building a Better Weather Sensor

Why Reinvent the Wheel?

Home Assistant used to have a built-in weather sensor with lots of useful details like the forecast. Unfortunately, this feature was removed in a recent update. But don't worry, we can recreate it using templates!

A word of caution: While creating complex templates can be fun and rewarding, remember that simpler templates are often better for system performance. So, let's aim to create a weather sensor that provides essential information without overwhelming your system.

Our Goal

We're going to build a custom weather sensor that looks and feels similar to the old one. It will include information like:

  • Current temperature
  • Humidity
  • Wind speed
  • Weather condition (sunny, cloudy, rainy, etc.)
  • A forecast for the next few days

By the end of this guide, you'll have a powerful weather sensor that provides all the information you need.

Let's start by breaking down the components of our template. In the next chapter, we'll dive into the trigger key.

Are you ready to get started?

Building Your Template

Deciding When to Refresh Your Weather - The Trigger Section

What is a Trigger?

A trigger is like a doorbell for your automation. It tells Home Assistant when to start running the template. In our case, we want to update the weather information regularly.

Two Ways to Schedule Updates

We'll focus on two main ways to trigger the weather update:

Home Assistant Event
  • Platform: homeassistant
  • Event: start - This option triggers the template when Home Assistant starts. While simple, it might not be ideal for frequent updates.
trigger:
  - platform: homeassistant
    event: start
Time Pattern
  • Platform: time_pattern
  • Hours: /1 - This option triggers the template every hour. For more frequent updates, you can adjust the hours value (e.g., /2 for every two hours).
trigger:
  - platform: time_pattern
    hours: /1
Beyond These Options

While these two methods are common, Home Assistant offers many other trigger platforms, including:

  • Event: Triggered by specific events within Home Assistant.
  • State: Triggered when an entity changes state (e.g., a door sensor opening).
  • Webhook: Triggered when an external request is made to a specific webhook.

By understanding different triggers, you can create highly customized and efficient automations.

What Should Your Home Do? - The Action Section

The action section is where the magic happens. It defines what your template should do when triggered. For our weather sensor, we'll fetch weather data and create a sensor with the results.

Fetching Weather Forecasts

To get weather forecast information, we'll use the powerful weather.get_forecasts service. This service allows you to retrieve weather data for multiple locations in a single request, making it efficient and convenient for managing forecasts across various areas.

Example:

action:
  - service: weather.get_forecasts
    data:
      type: daily  # Adjust to "hourly" for hourly forecasts
      target:
        entity_id: 
          - weather.paris
          - weather.new_york
          - weather.tokyo
      response_variable: daily_forecasts  # Customize the variable name if needed

This action will fetch daily weather forecasts for the specified locations in your Home Assistant configuration (replace with your desired locations). Remember, you can easily modify the entity_id list to include the weather entities you're interested in.

Important Note: The specific weather data points available (e.g., temperature, humidity) may vary depending on the weather integration you're using. Consult your integration's documentation for details.

This revision emphasizes the flexibility of the approach and acknowledges potential variations in data availability based on the weather integration.

**Leveraging Sensor Data - The Sensor Section**

To create a truly informative and visually appealing weather sensor, we can leverage the power of templates to customize its appearance and behavior.

sensor:
  - name: Weather Daily Paris
    state: "{{ states('weather.paris') }}"
    picture: >
      {% if states['weather.paris'].state == 'clear-day' %}/local/images/weather/sunny.png
      {% elif states['weather.paris'].state == 'clear-night' %}/local/images/weather/clear_night.png
      {% elif states['weather.paris'].state == 'cloudy' %}/local/images/weather/cloudy.png
      {% elif states['weather.paris'].state == 'overcast' %}/local/images/weather/cloudy.png
      {% elif states['weather.paris'].state == 'fog' %}/local/images/weather/fog.png
      {% elif states['weather.paris'].state == 'hail' %}/local/images/weather/mixed_rain.png
      {% elif states['weather.paris'].state == 'lightning' %}/local/images/weather/lightning.png
      {% elif states['weather.paris'].state == 'lightning-rainy' %}/local/images/weather/storm.png
      {% elif states['weather.paris'].state == 'partly-cloudy-day' %}/local/images/weather/mostly_cloudy.png
      {% elif states['weather.paris'].state == 'partly-cloudy-night' %}/local/images/weather/mostly_cloudy_night.png
      {% elif states['weather.paris'].state == 'partlycloudy' %}/local/images/weather/mostly_cloudy.png
      {% elif states['weather.paris'].state == 'pouring' %}/local/images/weather/heavy_rain.png
      {% elif states['weather.paris'].state == 'rain' %}/local/images/weather/rainy.png
      {% elif states['weather.paris'].state == 'rainy' %}/local/images/weather/rainy.png
      {% elif states['weather.paris'].state == 'sleet' %}/local/images/weather/mixed_rain.png
      {% elif states['weather.paris'].state == 'snow' %}/local/images/weather/snowy.png
      {% elif states['weather.paris'].state == 'snowy' %}/local/images/weather/snowy.png
      {% elif states['weather.paris'].state == 'snowy-rainy' %}/local/images/weather/mixed_rain.png
      {% elif states['weather.paris'].state == 'sunny' %}/local/images/weather/sunny.png
      {% elif states['weather.paris'].state == 'wind' %}/local/images/weather/windy.png
      {% elif states['weather.paris'].state == 'windy' %}/local/images/weather/windy.png
      {% elif states['weather.paris'].state == 'windy-variant' %}/local/images/weather/windy.png
      {% elif states['weather.paris'].state == 'humidity' %}/local/images/weather/humidity.png
      {% elif states['weather.paris'].state == 'pressure' %}/local/images/weather/pressure.png
      {% endif %}
    attributes:
      temperature: "{{ state_attr('weather.paris', 'temperature') }}"
      dew_point: "{{ state_attr('weather.paris', 'dew_point') }}"
      temperature_unit: "{{ state_attr('weather.paris', 'temperature_unit') }}"
      humidity: "{{ state_attr('weather.paris', 'humidity') }}"
      cloud_coverage: "{{ state_attr('weather.paris', 'cloud_coverage') }}"
      pressure: "{{ state_attr('weather.paris', 'pressure') }}"
      pressure_unit: "{{ state_attr('weather.paris', 'pressure_unit') }}"
      wind_bearing: "{{ state_attr('weather.paris', 'wind_bearing') }}"
      wind_speed: "{{ state_attr('weather.paris', 'wind_speed') }}"
      wind_speed_unit: "{{ state_attr('weather.paris', 'wind_speed_unit') }}"
      visibility_unit: "{{ state_attr('weather.paris', 'visibility_unit') }}"
      precipitation_unit: "{{ state_attr('weather.paris', 'precipitation_unit') }}"
      forecast: "{{ daily_forecasts['weather.paris'].forecast }}"

Let's break down the template provided:

  • Name: This defines the name of the sensor, which will be displayed in the Home Assistant interface. In this case, it's "Weather Daily Paris."
  • State: The state property determines the main value displayed by the sensor. Here, it's set to the state of the weather.paris entity. This is used for basic information display: we just want to keep the content of the actual weather sensor
  • Picture: This dynamically assigns an image based on the current weather state using conditional statements. You can customize the image paths (/local/images/weather/...) and potentially the weather conditions that trigger specific images based on your preferences and weather integration.
  • Attributes: This section defines additional details about the weather conditions. It includes temperature, dew point, humidity, wind speed, and other relevant data points. These attributes can be used to display information in the sensor's card or used in other automations. Here again, it’s a basic copy of the original weather sensor attributes
  • Forecast: This attribute leverages the data fetched using the weather.get_forecasts service explained in the previous chapter. It stores the forecast information for Paris, which can be an array containing details for multiple days depending on your weather integration.

By combining these elements, you can create a comprehensive weather sensor in Home Assistant. Remember to replace the placeholder image paths with your actual image files, and easily replicate this template for different locations to build a robust weather monitoring system.

Bringing It All Together

Now that we've covered the essential components, let's assemble a complete template for our weather sensor.

The full template

trigger:
  - platform: time_pattern
    hours: /1
  - platform: homeassistant
    event: start
action:
  - service: weather.get_forecasts
    data:
      type: daily
    target:
      entity_id: 
        - weather.paris
        - weather.new_york
        - weather.tokyo
    response_variable: daily_forecasts
sensor:
  - name: Weather Daily Paris
    state: "{{ states('weather.paris') }}"
    picture: >
      {% if states['weather.paris'].state == 'clear-day' %}/local/images/weather/sunny.png
      {% elif states['weather.paris'].state == 'clear-night' %}/local/images/weather/clear_night.png
      {% elif states['weather.paris'].state == 'cloudy' %}/local/images/weather/cloudy.png
      {% elif states['weather.paris'].state == 'overcast' %}/local/images/weather/cloudy.png
      {% elif states['weather.paris'].state == 'fog' %}/local/images/weather/fog.png
      {% elif states['weather.paris'].state == 'hail' %}/local/images/weather/mixed_rain.png
      {% elif states['weather.paris'].state == 'lightning' %}/local/images/weather/lightning.png
      {% elif states['weather.paris'].state == 'lightning-rainy' %}/local/images/weather/storm.png
      {% elif states['weather.paris'].state == 'partly-cloudy-day' %}/local/images/weather/mostly_cloudy.png
      {% elif states['weather.paris'].state == 'partly-cloudy-night' %}/local/images/weather/mostly_cloudy_night.png
      {% elif states['weather.paris'].state == 'partlycloudy' %}/local/images/weather/mostly_cloudy.png
      {% elif states['weather.paris'].state == 'pouring' %}/local/images/weather/heavy_rain.png
      {% elif states['weather.paris'].state == 'rain' %}/local/images/weather/rainy.png
      {% elif states['weather.paris'].state == 'rainy' %}/local/images/weather/rainy.png
      {% elif states['weather.paris'].state == 'sleet' %}/local/images/weather/mixed_rain.png
      {% elif states['weather.paris'].state == 'snow' %}/local/images/weather/snowy.png
      {% elif states['weather.paris'].state == 'snowy' %}/local/images/weather/snowy.png
      {% elif states['weather.paris'].state == 'snowy-rainy' %}/local/images/weather/mixed_rain.png
      {% elif states['weather.paris'].state == 'sunny' %}/local/images/weather/sunny.png
      {% elif states['weather.paris'].state == 'wind' %}/local/images/weather/windy.png
      {% elif states['weather.paris'].state == 'windy' %}/local/images/weather/windy.png
      {% elif states['weather.paris'].state == 'windy-variant' %}/local/images/weather/windy.png
      {% elif states['weather.paris'].state == 'humidity' %}/local/images/weather/humidity.png
      {% elif states['weather.paris'].state == 'pressure' %}/local/images/weather/pressure.png
      {% endif %}
    attributes:
      temperature: "{{ state_attr('weather.paris', 'temperature') }}"
      dew_point: "{{ state_attr('weather.paris', 'dew_point') }}"
      temperature_unit: "{{ state_attr('weather.paris', 'temperature_unit') }}"
      humidity: "{{ state_attr('weather.paris', 'humidity') }}"
      cloud_coverage: "{{ state_attr('weather.paris', 'cloud_coverage') }}"
      pressure: "{{ state_attr('weather.paris', 'pressure') }}"
      pressure_unit: "{{ state_attr('weather.paris', 'pressure_unit') }}"
      wind_bearing: "{{ state_attr('weather.paris', 'wind_bearing') }}"
      wind_speed: "{{ state_attr('weather.paris', 'wind_speed') }}"
      wind_speed_unit: "{{ state_attr('weather.paris', 'wind_speed_unit') }}"
      visibility_unit: "{{ state_attr('weather.paris', 'visibility_unit') }}"
      precipitation_unit: "{{ state_attr('weather.paris', 'precipitation_unit') }}"
      forecast: "{{ daily_forecasts['weather.paris'].forecast }}"
  - name: Weather Daily New York
    state: "{{ states('weather.new_york') }}"
        # Repeat the same picture and attribute, with a differnt the entity_id
  - name: Weather Daily Tokyo
    state: "{{ states('weather.tokyo') }}"
        # Repeat the same picture and attribute, with a differnt the entity_id

To use it, you need to add this as an array item of the template: key, inside your configuration.yaml file.

Conclusion and Further Exploration

Wrapping Up

You've now mastered the fundamentals of creating complex templates in Home Assistant, with a focus on building robust weather sensors. By combining triggers, actions, and custom sensors, you can create highly informative and personalized automations.

Remember to experiment with different weather integrations, explore additional data points, and refine your templates to match your specific needs.

Going Beyond the Basics

While we've covered the templates core concepts, there's still plenty to explore:

  • Advanced template logic: Dive deeper into template language to create complex conditions and calculations.
  • Visualizations: Use custom cards or dashboards to display weather information effectively.
  • Integrations: Combine weather data with other systems (e.g., smart home devices, calendars) for advanced automations.

By continuously learning and experimenting, you can unlock the full potential of Home Assistant and create truly impressive smart home solutions.

Happy automating!

You liked the post? Consider donating!
Become a patron
Buy me a coffee