mirror of
https://github.com/home-assistant/core.git
synced 2025-04-26 10:17:51 +00:00
Add float() operator to templates
This commit is contained in:
parent
eb5f208a09
commit
db4bf7319f
@ -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."""
|
||||
|
||||
|
@ -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)
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user