mirror of
https://github.com/home-assistant/core.git
synced 2025-07-19 11:17:21 +00:00
Add urlencode template filter (#37753)
* add urlencode template filter * fix flake8 * add test to string ang integer * better test vectors
This commit is contained in:
parent
34c2579507
commit
dbcd5f4c2c
@ -9,6 +9,7 @@ import math
|
|||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
from typing import Any, Dict, Iterable, List, Optional, Union
|
from typing import Any, Dict, Iterable, List, Optional, Union
|
||||||
|
from urllib.parse import urlencode as urllib_urlencode
|
||||||
|
|
||||||
import jinja2
|
import jinja2
|
||||||
from jinja2 import contextfilter, contextfunction
|
from jinja2 import contextfilter, contextfunction
|
||||||
@ -945,6 +946,11 @@ def relative_time(value):
|
|||||||
return dt_util.get_age(value)
|
return dt_util.get_age(value)
|
||||||
|
|
||||||
|
|
||||||
|
def urlencode(value):
|
||||||
|
"""Urlencode dictionary and return as UTF-8 string."""
|
||||||
|
return urllib_urlencode(value).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
class TemplateEnvironment(ImmutableSandboxedEnvironment):
|
class TemplateEnvironment(ImmutableSandboxedEnvironment):
|
||||||
"""The Home Assistant template environment."""
|
"""The Home Assistant template environment."""
|
||||||
|
|
||||||
@ -1001,6 +1007,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
|
|||||||
self.globals["as_timestamp"] = forgiving_as_timestamp
|
self.globals["as_timestamp"] = forgiving_as_timestamp
|
||||||
self.globals["relative_time"] = relative_time
|
self.globals["relative_time"] = relative_time
|
||||||
self.globals["strptime"] = strptime
|
self.globals["strptime"] = strptime
|
||||||
|
self.globals["urlencode"] = urlencode
|
||||||
if hass is None:
|
if hass is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -1872,3 +1872,16 @@ def test_render_complex_handling_non_template_values(hass):
|
|||||||
assert template.render_complex(
|
assert template.render_complex(
|
||||||
{True: 1, False: template.Template("{{ hello }}", hass)}, {"hello": 2}
|
{True: 1, False: template.Template("{{ hello }}", hass)}, {"hello": 2}
|
||||||
) == {True: 1, False: "2"}
|
) == {True: 1, False: "2"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_urlencode(hass):
|
||||||
|
"""Test the urlencode method."""
|
||||||
|
tpl = template.Template(
|
||||||
|
("{% set dict = {'foo': 'x&y', 'bar': 42} %}" "{{ dict | urlencode }}"), hass,
|
||||||
|
)
|
||||||
|
assert tpl.async_render() == "foo=x%26y&bar=42"
|
||||||
|
tpl = template.Template(
|
||||||
|
("{% set string = 'the quick brown fox = true' %}" "{{ string | urlencode }}"),
|
||||||
|
hass,
|
||||||
|
)
|
||||||
|
assert tpl.async_render() == "the%20quick%20brown%20fox%20%3D%20true"
|
||||||
|
Loading…
x
Reference in New Issue
Block a user