Is it possible to set a variable in the value_template of a template sensor for use in an attributes_template of the same template sensor? Or is there an altogether better way to achieve what I’m after? Thanks!
In the YAML below, I would like to use the variable type
to form part of the entity name in the scheduled
attributes template. With this code the attribute does not get defined.
- platform: template
sensors:
next_waste_collection:
friendly_name: Waste Collection
value_template: >-
{% if states.sensor.recycling_black_bin.attributes.next_date < states.sensor.recycling_garden.attributes.next_date %}
Recycling + Black Bin
{% set type = "black_bin" %}
{% else %}
Recycling + Garden Waste
{% set type = "garden" %}
{% endif %}
attribute_templates:
scheduled: >-
{% if (as_timestamp(now()) | timestamp_custom('%D')) == ((as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%D'))) %}
Today
{% elif (as_timestamp(now() + timedelta(days=1)) | timestamp_custom('%D')) == ((as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%D'))) %}
Tomorrow
{% else %}
{{ as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%A') }}
{% endif %}
If I set the variable directly in the attributes_template as below, the attribute gets defined correctly of course.
attribute_templates:
scheduled: >-
{% set type = "garden" %}
{% if (as_timestamp(now()) | timestamp_custom('%D')) == ((as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%D'))) %}
Today
{% elif (as_timestamp(now() + timedelta(days=1)) | timestamp_custom('%D')) == ((as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%D'))) %}
Tomorrow
{% else %}
{{ as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%A') }}
{% endif %}
Also, in Dev Tools/Templates…
{% if state_attr('sensor.recycling_black_bin', 'next_date') < state_attr('sensor.recycling_garden', 'next_date') %}
Recycling + Black Bin
{% set type = 'black_bin' %}
{% else %}
Recycling + Garden Waste
{% set type = 'garden' %}
{% endif %}
{% if (as_timestamp(now()) | timestamp_custom('%D')) == ((as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%D'))) %}
Today
{% elif (as_timestamp(now() + timedelta(days=1)) | timestamp_custom('%D')) == ((as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%D'))) %}
Tomorrow
{% else %}
{{ as_timestamp(state_attr('sensor.recycling_' ~ type, 'next_date')) | timestamp_custom('%A') }}
{% endif %}
…gives the result I’m after:
Recycling + Garden Waste
Tuesday
So, I assume that the variable definition is not shared between main value_template and attribute_templates when setting up a template sensor as it is between the two blocks in Dev Tools/Templates.