From d20a620590bc2df74eb2f9c0d35e1b7f12be5ded Mon Sep 17 00:00:00 2001 From: akloeckner Date: Wed, 20 Apr 2022 15:30:17 +0200 Subject: [PATCH] Make `this` variable available in template entities (#65201) * feat: make this variable available in template entities This makes the variable `this` available in template entities. It will simplify the use of self-referencing template entities. Because, without this, we have to repeat the entity id every time. If we can solve this without explicitly spelling the entity id, code can be re-used much better. As a side-effect, this will allow to use `variables`-like patterns, where attributes can be used as variables to calculate subsequent attributes or state. Example: ```yaml template: sensor: - name: test state: "{{ this.attributes.test }}" # not: "{{ state_attr('sensor.test', 'test' }}" attributes: test: "{{ now() }}" ``` * expose entity_id instead of this * add test * Refactor to expose this variable * Tweak repr dunder Co-authored-by: Erik --- .../components/template/template_entity.py | 11 +++- homeassistant/helpers/template.py | 51 ++++++++++++++++--- tests/components/template/test_sensor.py | 29 +++++++++++ 3 files changed, 81 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/template/template_entity.py b/homeassistant/components/template/template_entity.py index 5e592e5d717..d7d6ab46c62 100644 --- a/homeassistant/components/template/template_entity.py +++ b/homeassistant/components/template/template_entity.py @@ -27,7 +27,11 @@ from homeassistant.helpers.event import ( TrackTemplateResult, async_track_template_result, ) -from homeassistant.helpers.template import Template, result_as_boolean +from homeassistant.helpers.template import ( + Template, + TemplateStateFromEntityId, + result_as_boolean, +) from .const import ( CONF_ATTRIBUTE_TEMPLATES, @@ -368,8 +372,11 @@ class TemplateEntity(Entity): async def _async_template_startup(self, *_) -> None: template_var_tups: list[TrackTemplate] = [] has_availability_template = False + + values = {"this": TemplateStateFromEntityId(self.hass, self.entity_id)} + for template, attributes in self._template_attrs.items(): - template_var_tup = TrackTemplate(template, None) + template_var_tup = TrackTemplate(template, values) is_availability_template = False for attribute in attributes: # pylint: disable-next=protected-access diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 9003fc2daf3..a8eb96c5ad1 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -719,22 +719,24 @@ class DomainStates: return f"