Greetings,
I’m writing a Template Sensor which has to be ON when a specific Template has triggered but I’m facing a boring things: I have to triplicate statements.
The most semplified version of my Template sensor is this:
- trigger:
- platform: template
value_template: >-
{{ expand('group.abcd') | rejectattr("entity_id", "in", ['switch.on_off']) | selectattr('state', 'eq', 'on') | list | count > 0 }}
- platform: template
value_template: >-
{{ expand('group.abcd') | rejectattr("entity_id", "in", ['switch.on_off']) | selectattr('state', 'eq', 'on') | list | count <= 0 }}
action:
- variables:
entities_on: >-
{{ expand('group.abcd') | rejectattr("entity_id", "in", ['switch.on_off']) | selectattr('state', 'eq', 'on') | list | count }}
binary_sensor:
- name: Cucina attiva
state: >-
{{ (entities_on | int(0) > 0) }}
As you can see the Jinja part from “expand()” to “…| list | count” have to be replicated three times to achieve the right result:
- two times for Template Sensor triggers
- one time for the State
Without the “action” part I would have have write a “variables” section in each trigger and more than three replications would have beed needed, so something is already done to avoid replications but I think it could be done something more.
I mean something like this (UPPERCASE parts relevants):
- trigger:
- platform: template
value_template: "{{ ENTITIES_COUNT > 0 }}"
- platform: template
value_template: "{{ ENTITIES_COUNT <= 0 }}"
VARIABLES:
- ENTITIES_COUNT: >-
{{ expand('group.abcd') | rejectattr("entity_id", "in", ['switch.on_off']) | selectattr('state', 'eq', 'on') | list | count }}
binary_sensor:
- name: Cucina attiva
state: >-
{{ (ENTITIES_COUNT | int(0) > 0) }}
or just let that a “trigger_variables” section be resposable to create entities Listeners AND those variables that can be used in the whole Sensor Template.
At this moment this is how variables works but…:
- we can add a “variables” section for each Trigger BUT these variables are not shared across Triggers
- we can add an “action” section to declare variables BUT these are evaluated only after the trigger execution
- each trigger “variables” section doesn’t shares its values with “action” section
- “trigger_variables” section here is not useful for the obliviously reason