mirror of
https://github.com/home-assistant/core.git
synced 2025-07-19 03:07:37 +00:00
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:
parent
1e35dd9f6f
commit
cc99a9b62a
@ -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
|
||||
|
@ -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 = [
|
||||
|
Loading…
x
Reference in New Issue
Block a user