From 26dc52623417c4a9c7a65f14e4ecd9e6d0f5103f Mon Sep 17 00:00:00 2001 From: Brynley McDonald Date: Tue, 21 Dec 2021 23:35:54 +1300 Subject: [PATCH] Add slugify as a template filter (#58724) --- homeassistant/helpers/template.py | 14 +++++++++++++- tests/helpers/test_template.py | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 0ba1d6bfa14..2a605561572 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -53,7 +53,12 @@ from homeassistant.helpers import ( ) from homeassistant.helpers.typing import TemplateVarsType from homeassistant.loader import bind_hass -from homeassistant.util import convert, dt as dt_util, location as loc_util +from homeassistant.util import ( + convert, + dt as dt_util, + location as loc_util, + slugify as slugify_util, +) from homeassistant.util.async_ import run_callback_threadsafe from homeassistant.util.thread import ThreadWithException @@ -1753,6 +1758,11 @@ def urlencode(value): return urllib_urlencode(value).encode("utf-8") +def slugify(value, separator="_"): + """Convert a string into a slug, such as what is used for entity ids.""" + return slugify_util(value, separator=separator) + + @contextmanager def set_template(template_str: str, action: str) -> Generator: """Store template being parsed or rendered in a Contextvar to aid error handling.""" @@ -1866,6 +1876,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.filters["float"] = forgiving_float_filter self.filters["int"] = forgiving_int_filter self.filters["relative_time"] = relative_time + self.filters["slugify"] = slugify self.globals["log"] = logarithm self.globals["sin"] = sine self.globals["cos"] = cosine @@ -1894,6 +1905,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.globals["int"] = forgiving_int self.globals["pack"] = struct_pack self.globals["unpack"] = struct_unpack + self.globals["slugify"] = slugify self.tests["match"] = regex_match self.tests["search"] = regex_search diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 4a97b99d05d..42a725eaff5 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -865,6 +865,26 @@ def test_base64_decode(hass): ) +def test_slugify(hass): + """Test the slugify filter.""" + assert ( + template.Template('{{ slugify("Home Assistant") }}', hass).async_render() + == "home_assistant" + ) + assert ( + template.Template('{{ "Home Assistant" | slugify }}', hass).async_render() + == "home_assistant" + ) + assert ( + template.Template('{{ slugify("Home Assistant", "-") }}', hass).async_render() + == "home-assistant" + ) + assert ( + template.Template('{{ "Home Assistant" | slugify("-") }}', hass).async_render() + == "home-assistant" + ) + + def test_ordinal(hass): """Test the ordinal filter.""" tests = [