mirror of
https://github.com/home-assistant/core.git
synced 2025-04-28 11:17:53 +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, {
|
return ENV.from_string(template, {
|
||||||
'closest': location_methods.closest,
|
'closest': location_methods.closest,
|
||||||
'distance': location_methods.distance,
|
'distance': location_methods.distance,
|
||||||
|
'float': forgiving_float,
|
||||||
'is_state': hass.states.is_state,
|
'is_state': hass.states.is_state,
|
||||||
'is_state_attr': hass.states.is_state_attr,
|
'is_state_attr': hass.states.is_state_attr,
|
||||||
'now': dt_util.as_local(utcnow),
|
'now': dt_util.as_local(utcnow),
|
||||||
@ -240,6 +241,14 @@ def multiply(value, amount):
|
|||||||
return value
|
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):
|
class TemplateEnvironment(ImmutableSandboxedEnvironment):
|
||||||
"""Home Assistant template environment."""
|
"""Home Assistant template environment."""
|
||||||
|
|
||||||
|
@ -51,6 +51,21 @@ class TestUtilTemplate(unittest.TestCase):
|
|||||||
{% for state in states.sensor %}{{ state.state }}{% endfor %}
|
{% 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):
|
def test_rounding_value(self):
|
||||||
self.hass.states.set('sensor.temperature', 12.78)
|
self.hass.states.set('sensor.temperature', 12.78)
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user