mirror of
https://github.com/home-assistant/core.git
synced 2025-04-25 09:47:52 +00:00
Add multiply template filter
This commit is contained in:
parent
b440c260e6
commit
af09a305cf
@ -10,16 +10,25 @@ from jinja2.sandbox import SandboxedEnvironment
|
||||
ENV = SandboxedEnvironment()
|
||||
|
||||
|
||||
def forgiving_round(value, precision):
|
||||
def forgiving_round(value, precision=0):
|
||||
""" Rounding method that accepts strings. """
|
||||
try:
|
||||
return round(float(value), precision)
|
||||
return int(value) if precision == 0 else round(float(value), precision)
|
||||
except ValueError:
|
||||
# If value can't be converted to float
|
||||
return value
|
||||
|
||||
|
||||
def multiply(value, amount):
|
||||
""" Converts to float and multiplies value. """
|
||||
try:
|
||||
return float(value) * amount
|
||||
except ValueError:
|
||||
# If value can't be converted to float
|
||||
return value
|
||||
|
||||
ENV.filters['round'] = forgiving_round
|
||||
ENV.filters['multiply'] = multiply
|
||||
|
||||
|
||||
def render(hass, template):
|
||||
|
@ -55,3 +55,12 @@ class TestUtilTemplate(unittest.TestCase):
|
||||
template.render(
|
||||
self.hass,
|
||||
'{{ states.sensor.temperature.state | round(1) }}'))
|
||||
|
||||
def test_rounding_value2(self):
|
||||
self.hass.states.set('sensor.temperature', 12.34)
|
||||
|
||||
self.assertEqual(
|
||||
'123',
|
||||
template.render(
|
||||
self.hass,
|
||||
'{{ states.sensor.temperature.state | multiply(10) | round }}'))
|
||||
|
Loading…
x
Reference in New Issue
Block a user