Add template function: typeof (#140081)

This commit is contained in:
Franck Nijhof 2025-03-08 20:16:21 +01:00 committed by GitHub
parent d94bdb7ecd
commit e54febdc1e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 0 deletions

View File

@ -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

View File

@ -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"
)