diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index fd2c11e4eb9..e8c169e92d8 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1879,8 +1879,12 @@ def is_state(hass: HomeAssistant, entity_id: str, state: str | list[str]) -> boo def is_state_attr(hass: HomeAssistant, entity_id: str, name: str, value: Any) -> bool: """Test if a state's attribute is a specific value.""" - attr = state_attr(hass, entity_id, name) - return attr is not None and attr == value + if (state_obj := _get_state(hass, entity_id)) is not None: + attr = state_obj.attributes.get(name, _SENTINEL) + if attr is _SENTINEL: + return False + return bool(attr == value) + return False def state_attr(hass: HomeAssistant, entity_id: str, name: str) -> Any: diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 628aea20900..ab0f126eaa9 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1970,7 +1970,7 @@ def test_is_state(hass: HomeAssistant) -> None: def test_is_state_attr(hass: HomeAssistant) -> None: """Test is_state_attr method.""" - hass.states.async_set("test.object", "available", {"mode": "on"}) + hass.states.async_set("test.object", "available", {"mode": "on", "exists": None}) tpl = template.Template( """ {% if is_state_attr("test.object", "mode", "on") %}yes{% else %}no{% endif %} @@ -2003,6 +2003,22 @@ def test_is_state_attr(hass: HomeAssistant) -> None: ) assert tpl.async_render() == "test.object" + tpl = template.Template( + """ +{% if is_state_attr("test.object", "exists", None) %}yes{% else %}no{% endif %} + """, + hass, + ) + assert tpl.async_render() == "yes" + + tpl = template.Template( + """ +{% if is_state_attr("test.object", "noexist", None) %}yes{% else %}no{% endif %} + """, + hass, + ) + assert tpl.async_render() == "no" + def test_state_attr(hass: HomeAssistant) -> None: """Test state_attr method."""