Add float() operator to templates

This commit is contained in:
Dan Smith 2016-02-24 10:41:49 -08:00
parent eb5f208a09
commit db4bf7319f
2 changed files with 24 additions and 0 deletions

View File

@ -52,6 +52,7 @@ def render(hass, template, variables=None, **kwargs):
return ENV.from_string(template, {
'closest': location_methods.closest,
'distance': location_methods.distance,
'float': forgiving_float,
'is_state': hass.states.is_state,
'is_state_attr': hass.states.is_state_attr,
'now': dt_util.as_local(utcnow),
@ -240,6 +241,14 @@ def multiply(value, amount):
return value
def forgiving_float(value):
"""Try to convert value to a float."""
try:
return float(value)
except (ValueError, TypeError):
return value
class TemplateEnvironment(ImmutableSandboxedEnvironment):
"""Home Assistant template environment."""

View File

@ -51,6 +51,21 @@ class TestUtilTemplate(unittest.TestCase):
{% for state in states.sensor %}{{ state.state }}{% endfor %}
"""))
def test_float(self):
self.hass.states.set('sensor.temperature', '12')
self.assertEqual(
'12.0',
template.render(
self.hass,
'{{ float(states.sensor.temperature.state) }}'))
self.assertEqual(
'True',
template.render(
self.hass,
'{{ float(states.sensor.temperature.state) > 11 }}'))
def test_rounding_value(self):
self.hass.states.set('sensor.temperature', 12.78)