1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 21:06:19 +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:
Troon
2024-05-08 14:39:36 +01:00
committed by GitHub
parent 1e35dd9f6f
commit cc99a9b62a
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