diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index ab115203e66cb75cf2bc916e9d760f0737c2a388..e5a155a5c36995f0210e4ec351acac2d4d4c0d30 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -2760,6 +2760,11 @@ def shuffle(*args: Any, seed: Any = None) -> MutableSequence[Any]: return items +def typeof(value: Any) -> Any: + """Return the type of value passed to debug types.""" + return value.__class__.__name__ + + class TemplateContextManager(AbstractContextManager): """Context manager to store template being parsed or rendered in a ContextVar.""" @@ -2961,6 +2966,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.filters["version"] = version self.filters["contains"] = contains self.filters["shuffle"] = shuffle + self.filters["typeof"] = typeof self.globals["log"] = logarithm self.globals["sin"] = sine self.globals["cos"] = cosine @@ -2999,6 +3005,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.globals["version"] = version self.globals["zip"] = zip self.globals["shuffle"] = shuffle + self.globals["typeof"] = typeof self.tests["is_number"] = is_number self.tests["list"] = _is_list self.tests["set"] = _is_set diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 28391d97a3ca9828d5999e3991e0ef87a1abd49b..5ae821bce24417f6755e71e35414af81fef08161 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -6724,3 +6724,30 @@ def test_shuffle(hass: HomeAssistant) -> None: with pytest.raises(TemplateError): template.Template("{{ shuffle() }}", hass).async_render() + + +def test_typeof(hass: HomeAssistant) -> None: + """Test the typeof debug filter/function.""" + assert template.Template("{{ True | typeof }}", hass).async_render() == "bool" + assert template.Template("{{ typeof(True) }}", hass).async_render() == "bool" + + assert template.Template("{{ [1, 2, 3] | typeof }}", hass).async_render() == "list" + assert template.Template("{{ typeof([1, 2, 3]) }}", hass).async_render() == "list" + + assert template.Template("{{ 1 | typeof }}", hass).async_render() == "int" + assert template.Template("{{ typeof(1) }}", hass).async_render() == "int" + + assert template.Template("{{ 1.1 | typeof }}", hass).async_render() == "float" + assert template.Template("{{ typeof(1.1) }}", hass).async_render() == "float" + + assert template.Template("{{ None | typeof }}", hass).async_render() == "NoneType" + assert template.Template("{{ typeof(None) }}", hass).async_render() == "NoneType" + + assert ( + template.Template("{{ 'Home Assistant' | typeof }}", hass).async_render() + == "str" + ) + assert ( + template.Template("{{ typeof('Home Assistant') }}", hass).async_render() + == "str" + )