Could anyone see what I have done wrong here? I thought this should work, but there is something HA is interpreting that I cannot catch. Also I find this very hard to test in the templating tool. Do you have a suggestion how I could debug the problem further?
You canât template the entire attributes section of a template entity. And if you were able to do that, youâd have to return a dictionary in JSON, not yaml.
Thanks! The error comes when I boot HA and the code is as posted. The code is from configuration.yaml but I also struggle to understand the logged error.
But when you say I cannon use jinja2 in a template sensor, then I do not understand how this works:
Cool, I think now I understand both what you are saying, and I think this is a workable solution. Thanks to both @123 and @petro for helping me better understand the logic.
If anyone wants to use this in the future, I just have to mention there was a missing paranthesis and some wrong logic for the cond_icon. Though that was simple to fix. Here is the corrected code (also updated the state):
- trigger:
- platform: time_pattern
hours: /1
- platform: homeassistant
event: start
action:
- service: weather.get_forecasts
data:
type: daily
response_variable: daily
target:
entity_id: weather.rykkinn
sensor:
- name: "Weather Now and Daily"
unique_id: weather_now_daily
state: "{{ daily['weather.rykkinn'].forecast[0].condition }}"
attributes:
condition: "{{ daily['weather.rykkinn'].forecast[0].condition }}"
cond_icon: >
{% set weather = daily['weather.rykkinn'].forecast[0].condition %}
{% if is_state('sun.sun', 'above_horizon') %}
{{ '/local/ic/weather_icons/animated3/' + weather + '.svg' }}
{% else %}
{{ '/local/ic/weather_icons/animated3/' + weather + '_night.svg' }}
{% endif %}
temperature: "{{ daily['weather.rykkinn'].forecast[0].temperature }}"
feels_like: "{{ daily['weather.rykkinn'].forecast[0].condition }}"
precipitation: "{{ daily['weather.rykkinn'].forecast[0].precipitation }}"
precipitation_percent: "{{ daily['weather.rykkinn'].forecast[0].precipitation_probability }}"
wind_dir: "{{ daily['weather.rykkinn'].forecast[0].wind_bearing }}"
wind_speed: "{{ daily['weather.rykkinn'].forecast[0].wind_speed }}"
wind_gust_speed: "{{ daily['weather.rykkinn'].forecast[0].wind_gust_speed }}"
forecast: >
{% set ns = namespace(items=[]) %}
{% set keys = ['temperature', 'precipitation', 'datetime', 'condition'] %}
{% for i in range(1, 6) %}
{% for key in keys %}
{% set value = daily['weather.rykkinn'].forecast[i][key] %}
{% set ns.items = ns.items + [(key ~ i, value)] %}
{% if key == 'condition' %}
{% set icon = '' if is_state('sun.sun', 'above_horizon') else '_night' %}
{% set ns.items = ns.items + [('cond_icon' ~ i, '/local/ic/weather_icons/animated3/' ~ value ~ icon ~ '.svg')] %}
{% endif %}
{% endfor %}
{% endfor %}
{{ dict(ns.items) }}
To read the attribute I found that I have to write it this way: