From eed16dc185b9b04682b7589e49c084a9aeefab36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20Mind=C3=AAllo=20de=20Andrade?= Date: Thu, 9 Mar 2023 18:32:30 -0300 Subject: [PATCH] Add list areas function to template (#88441) --- homeassistant/helpers/template.py | 9 +++++++++ tests/helpers/test_template.py | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index c923bd2d84a..5205d51273f 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1185,6 +1185,12 @@ def is_device_attr( return bool(device_attr(hass, device_or_entity_id, attr_name) == attr_value) +def areas(hass: HomeAssistant) -> Iterable[str | None]: + """Return all areas.""" + area_reg = area_registry.async_get(hass) + return [area.id for area in area_reg.async_list_areas()] + + def area_id(hass: HomeAssistant, lookup_value: str) -> str | None: """Get the area ID from an area name, device id, or entity id.""" area_reg = area_registry.async_get(hass) @@ -2183,6 +2189,9 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.globals["device_id"] = hassfunction(device_id) self.filters["device_id"] = pass_context(self.globals["device_id"]) + self.globals["areas"] = hassfunction(areas) + self.filters["areas"] = pass_context(self.globals["areas"]) + self.globals["area_id"] = hassfunction(area_id) self.filters["area_id"] = pass_context(self.globals["area_id"]) diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index f97f0a4b9c5..5122a4238ea 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -2851,6 +2851,26 @@ async def test_device_attr( assert info.rate_limit is None +async def test_areas(hass: HomeAssistant, area_registry: ar.AreaRegistry) -> None: + """Test areas function.""" + # Test no areas + info = render_to_info(hass, "{{ areas() }}") + assert_result_info(info, []) + assert info.rate_limit is None + + # Test one area + area1 = area_registry.async_get_or_create("area1") + info = render_to_info(hass, "{{ areas() }}") + assert_result_info(info, [area1.id]) + assert info.rate_limit is None + + # Test multiple areas + area2 = area_registry.async_get_or_create("area2") + info = render_to_info(hass, "{{ areas() }}") + assert_result_info(info, [area1.id, area2.id]) + assert info.rate_limit is None + + async def test_area_id( hass: HomeAssistant, area_registry: ar.AreaRegistry,