diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 5a4d631a8c8..083d0e530aa 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1063,6 +1063,14 @@ def integration_entities(hass: HomeAssistant, entry_name: str) -> Iterable[str]: ] +def entry_id(hass: HomeAssistant, entity_id: str) -> str | None: + """Get an entry ID from an entity ID.""" + entity_reg = entity_registry.async_get(hass) + if entity := entity_reg.async_get(entity_id): + return entity.config_entry_id + return None + + def device_id(hass: HomeAssistant, entity_id_or_device_name: str) -> str | None: """Get a device ID from an entity ID or device name.""" entity_reg = entity_registry.async_get(hass) @@ -2072,6 +2080,9 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.globals["device_attr"] = hassfunction(device_attr) self.globals["is_device_attr"] = hassfunction(is_device_attr) + self.globals["entry_id"] = hassfunction(entry_id) + self.filters["entry_id"] = pass_context(self.globals["entry_id"]) + self.globals["device_id"] = hassfunction(device_id) self.filters["device_id"] = pass_context(self.globals["device_id"]) diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index fa9ec4e76d6..9c9a1e42a98 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -2458,6 +2458,30 @@ async def test_integration_entities(hass): assert info.rate_limit is None +async def test_entry_id(hass): + """Test entry_id function.""" + config_entry = MockConfigEntry(domain="light", title="Some integration") + config_entry.add_to_hass(hass) + entity_registry = mock_registry(hass) + entity_entry = entity_registry.async_get_or_create( + "sensor", "test", "test", suggested_object_id="test", config_entry=config_entry + ) + + info = render_to_info(hass, "{{ 'sensor.fail' | entry_id }}") + assert_result_info(info, None) + assert info.rate_limit is None + + info = render_to_info(hass, "{{ 56 | entry_id }}") + assert_result_info(info, None) + + info = render_to_info(hass, "{{ 'not_a_real_entity_id' | entry_id }}") + assert_result_info(info, None) + + info = render_to_info(hass, f"{{{{ entry_id('{entity_entry.entity_id}') }}}}") + assert_result_info(info, config_entry.entry_id) + assert info.rate_limit is None + + async def test_device_id(hass): """Test device_id function.""" config_entry = MockConfigEntry(domain="light")