I have a quite complicated sensor that evaluates the same value a few times. Something like this:
- platform: template
sensors:
rads_call_for_heat:
friendly_name: "Radiators Call for Heat"
icon_template: mdi:radiator
value_template: >
{% from 'macros.jinja' import
is_devs_calling_for_heat_by_label,
is_timers_active_by_label
%}
{{
is_timers_active_by_label('Heating Timers') | bool or
is_devs_calling_for_heat_by_label("TRV") | bool
}}
attribute_templates:
active_devices: >
{% from 'macros.jinja' import
devs_calling_for_heat_by_label,
timers_active_by_label
%}
{% set timers = timers_active_by_label('Heating Timers').split(',') %}
{% set trvs = devs_calling_for_heat_by_label('TRV').split(',') %}
{% set all_aux = trvs + timers %}
{% set all = all_aux | reject("==", '') | list %}
{{ all }}
active_places: >
{% from 'macros.jinja' import
devs_calling_for_heat_by_label,
timers_active_by_label
%}
{% set timers = timers_active_by_label('Heating Timers').split(',') %}
{% set trvs = devs_calling_for_heat_by_label('TRV').split(',') %}
{% set all_aux = trvs + timers %}
{% set all = all_aux | reject("==", '') | list %}
{{ all | map('area_name') | list }}
As you can see, both attributes have a very similar code, only changing the final value.
I’d love to reuse that code better. I wonder if is there a way to declare variables/namespace so it would be shared through the whole sensor context.
Something like this would be awesome:
- platform: template
sensors:
rads_call_for_heat:
friendly_name: "Radiators Call for Heat"
icon_template: mdi:radiator
namespace:
{% set ns = namespace(all=[]) -%}
{% from 'macros.jinja' import
devs_calling_for_heat_by_label,
timers_active_by_label
%}
{% set timers = timers_active_by_label('Heating Timers').split(',') %}
{% set trvs = devs_calling_for_heat_by_label('TRV').split(',') %}
{% set all_aux = trvs + timers %}
{% set ns.all = all_aux | reject("==", '') | list %}
{{ ns }}
value_template: "{{ ns.all | count > 0 }}"
attribute_templates:
active_devices: "{{ ns.all }}"
active_places: "{{ ns.all | map('area_name') | list }}"
Is it possible or feasible?
Thanks a lot!