Fix urlencode template function rendering as a bytes literal (#187629)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Raman Gupta
2026-10-21 08:02:07 +02:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 51b541d5e3
commit fba4dc8b09
2 changed files with 24 additions and 3 deletions
@@ -51,6 +51,6 @@ class StringExtension(BaseTemplateExtension):
"""Convert a string into a slug, such as what is used for entity ids."""
return slugify_util(str(value), separator=separator)
def urlencode(self, value: Any) -> bytes:
"""Urlencode dictionary and return as UTF-8 string."""
return urllib_urlencode(value).encode("utf-8")
def urlencode(self, value: Any) -> str:
"""Urlencode dictionary and return as string."""
return urllib_urlencode(value)
@@ -1,5 +1,7 @@
"""Test string template extension."""
import pytest
from homeassistant.core import HomeAssistant
from tests.helpers.template.helpers import render
@@ -54,6 +56,25 @@ def test_urlencode(hass: HomeAssistant) -> None:
assert result == "the%20quick%20brown%20fox%20%3D%20true"
@pytest.mark.parametrize(
("template_str", "expected"),
[
pytest.param("{{ urlencode({'a': 'b c'}) }}", "a=b+c", id="only_node"),
pytest.param("?{{ urlencode({'a': 'b c'}) }}", "?a=b+c", id="concatenated"),
pytest.param(
"{{ urlencode({'foo': 'x&y', 'bar': 42}) }}",
"foo=x%26y&bar=42",
id="special_characters",
),
],
)
def test_urlencode_function(
hass: HomeAssistant, template_str: str, expected: str
) -> None:
"""Test the urlencode function renders a query string."""
assert render(hass, template_str, parse_result=False) == expected
def test_string_functions_with_non_string_input(hass: HomeAssistant) -> None:
"""Test string functions with non-string input (automatic conversion)."""
# Test ordinal with integer