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
This commit is contained in:
akloeckner 2022-06-27 08:59:29 +02:00 committed by GitHub
parent 11ec8b9186
commit aa314a0901
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 13 deletions

View file

@ -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

View file

@ -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 }}"},
},
},
},