From aa314a090146b44d32ab2a2754321ae03bf248de Mon Sep 17 00:00:00 2001 From: akloeckner Date: Mon, 27 Jun 2022 08:59:29 +0200 Subject: [PATCH] Add this variable to trigger-based templates (#72437) add this variables to trigger-based templates follow-up for https://github.com/home-assistant/core/issues/70359 --- .../components/template/trigger_entity.py | 13 ++++++-- tests/components/template/test_sensor.py | 32 +++++++++++++------ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/homeassistant/components/template/trigger_entity.py b/homeassistant/components/template/trigger_entity.py index 6780d12c507..b5696003c94 100644 --- a/homeassistant/components/template/trigger_entity.py +++ b/homeassistant/components/template/trigger_entity.py @@ -147,25 +147,32 @@ class TriggerEntity(CoordinatorEntity[TriggerUpdateCoordinator]): @callback def _process_data(self) -> None: """Process new data.""" + + this = None + if state := self.hass.states.get(self.entity_id): + this = state.as_dict() + run_variables = self.coordinator.data["run_variables"] + variables = {"this": this, **(run_variables or {})} + try: rendered = dict(self._static_rendered) for key in self._to_render_simple: rendered[key] = self._config[key].async_render( - self.coordinator.data["run_variables"], + variables, parse_result=key in self._parse_result, ) for key in self._to_render_complex: rendered[key] = template.render_complex( self._config[key], - self.coordinator.data["run_variables"], + variables, ) if CONF_ATTRIBUTES in self._config: rendered[CONF_ATTRIBUTES] = template.render_complex( self._config[CONF_ATTRIBUTES], - self.coordinator.data["run_variables"], + variables, ) self._rendered = rendered diff --git a/tests/components/template/test_sensor.py b/tests/components/template/test_sensor.py index ddf13c2015b..44fa96cfc6a 100644 --- a/tests/components/template/test_sensor.py +++ b/tests/components/template/test_sensor.py @@ -624,20 +624,32 @@ async def test_sun_renders_once_per_sensor(hass, start_ha): } -@pytest.mark.parametrize("count,domain", [(1, sensor.DOMAIN)]) +@pytest.mark.parametrize("count,domain", [(1, "template")]) @pytest.mark.parametrize( "config", [ { - "sensor": { - "platform": "template", - "sensors": { - "test_template_sensor": { - "value_template": "{{ this.attributes.test }}: {{ this.entity_id }}", - "attribute_templates": { - "test": "It {{ states.sensor.test_state.state }}" - }, - } + "template": { + "sensor": { + "name": "test_template_sensor", + "state": "{{ this.attributes.test }}: {{ this.entity_id }}", + "attributes": {"test": "It {{ states.sensor.test_state.state }}"}, + }, + }, + }, + { + "template": { + "trigger": { + "platform": "state", + "entity_id": [ + "sensor.test_state", + "sensor.test_template_sensor", + ], + }, + "sensor": { + "name": "test_template_sensor", + "state": "{{ this.attributes.test }}: {{ this.entity_id }}", + "attributes": {"test": "It {{ states.sensor.test_state.state }}"}, }, }, },