Add an add template filter (#109884)

* Addition of add filter

This change adds an `add` filter, the addition equivalent of the existing `multiply` filter.

* Test for add filter

* Update test_template.py

* Update tests/helpers/test_template.py

---------

Co-authored-by: Erik Montnemery <erik@montnemery.com>
This commit is contained in:
Troon 2024-05-08 14:39:36 +01:00 committed by GitHub
parent 1e35dd9f6f
commit cc99a9b62a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 31 additions and 0 deletions

View File

@ -1888,6 +1888,17 @@ def multiply(value, amount, default=_SENTINEL):
return default
def add(value, amount, default=_SENTINEL):
"""Filter to convert value to float and add it."""
try:
return float(value) + amount
except (ValueError, TypeError):
# If value can't be converted to float
if default is _SENTINEL:
raise_no_default("add", value)
return default
def logarithm(value, base=math.e, default=_SENTINEL):
"""Filter and function to get logarithm of the value with a specific base."""
try:
@ -2728,6 +2739,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
self.add_extension("jinja2.ext.loopcontrols")
self.filters["round"] = forgiving_round
self.filters["multiply"] = multiply
self.filters["add"] = add
self.filters["log"] = logarithm
self.filters["sin"] = sine
self.filters["cos"] = cosine

View File

@ -721,6 +721,25 @@ def test_multiply(hass: HomeAssistant) -> None:
assert render(hass, "{{ 'no_number' | multiply(10, default=1) }}") == 1
def test_add(hass: HomeAssistant) -> None:
"""Test add."""
tests = {10: 42}
for inp, out in tests.items():
assert (
template.Template(f"{{{{ {inp} | add(32) | round }}}}", hass).async_render()
== out
)
# Test handling of invalid input
with pytest.raises(TemplateError):
template.Template("{{ abcd | add(10) }}", hass).async_render()
# Test handling of default return value
assert render(hass, "{{ 'no_number' | add(10, 1) }}") == 1
assert render(hass, "{{ 'no_number' | add(10, default=1) }}") == 1
def test_logarithm(hass: HomeAssistant) -> None:
"""Test logarithm."""
tests = [