Add trigger_variables to template trigger 'for' field (#136672)

* Add trigger_variables to template trigger for

* address comments
This commit is contained in:
Petro31 2025-05-19 11:26:42 -04:00 committed by GitHub
parent a8ecdb3bff
commit 752c73a2ed
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 40 additions and 5 deletions

View File

@ -48,6 +48,7 @@ async def async_attach_trigger(
) -> CALLBACK_TYPE:
"""Listen for state changes based on configuration."""
trigger_data = trigger_info["trigger_data"]
variables = trigger_info["variables"] or {}
value_template: Template = config[CONF_VALUE_TEMPLATE]
time_delta = config.get(CONF_FOR)
delay_cancel = None
@ -56,9 +57,7 @@ async def async_attach_trigger(
# Arm at setup if the template is already false.
try:
if not result_as_boolean(
value_template.async_render(trigger_info["variables"])
):
if not result_as_boolean(value_template.async_render(variables)):
armed = True
except exceptions.TemplateError as ex:
_LOGGER.warning(
@ -134,9 +133,12 @@ async def async_attach_trigger(
call_action()
return
data = {"trigger": template_variables}
period_variables = {**variables, **data}
try:
period: timedelta = cv.positive_time_period(
template.render_complex(time_delta, {"trigger": template_variables})
template.render_complex(time_delta, period_variables)
)
except (exceptions.TemplateError, vol.Invalid) as ex:
_LOGGER.error(
@ -150,7 +152,7 @@ async def async_attach_trigger(
info = async_track_template_result(
hass,
[TrackTemplate(value_template, trigger_info["variables"])],
[TrackTemplate(value_template, variables)],
template_listener,
)
unsub = info.async_remove

View File

@ -788,6 +788,39 @@ async def test_if_fires_on_change_with_for_template_3(
assert len(calls) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",
[
{
automation.DOMAIN: {
"trigger_variables": {
"seconds": 5,
"entity": "test.entity",
},
"trigger": {
"platform": "template",
"value_template": "{{ is_state(entity, 'world') }}",
"for": "{{ seconds }}",
},
"action": {"service": "test.automation"},
}
},
],
)
@pytest.mark.usefixtures("start_ha")
async def test_if_fires_on_change_with_for_template_4(
hass: HomeAssistant, calls: list[ServiceCall]
) -> None:
"""Test for firing on change with for template."""
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
@pytest.mark.parametrize(("count", "domain"), [(1, automation.DOMAIN)])
@pytest.mark.parametrize(
"config",