1
mirror of https://github.com/home-assistant/core synced 2024-10-04 07:58:43 +02:00

Make template states var callable

This commit is contained in:
Paulus Schoutsen 2015-12-12 22:19:37 -08:00
parent 360b99be59
commit f73f824e0e
2 changed files with 30 additions and 1 deletions

View File

@ -9,6 +9,7 @@ import json
import logging import logging
import jinja2 import jinja2
from jinja2.sandbox import ImmutableSandboxedEnvironment from jinja2.sandbox import ImmutableSandboxedEnvironment
from homeassistant.const import STATE_UNKNOWN
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -60,6 +61,10 @@ class AllStates(object):
return iter(sorted(self._hass.states.all(), return iter(sorted(self._hass.states.all(),
key=lambda state: state.entity_id)) key=lambda state: state.entity_id))
def __call__(self, entity_id):
state = self._hass.states.get(entity_id)
return STATE_UNKNOWN if state is None else state.state
class DomainStates(object): class DomainStates(object):
""" Class to expose a specific HA domain as attributes. """ """ Class to expose a specific HA domain as attributes. """
@ -96,6 +101,13 @@ def multiply(value, amount):
# If value can't be converted to float # If value can't be converted to float
return value return value
ENV = ImmutableSandboxedEnvironment()
class TemplateEnvironment(ImmutableSandboxedEnvironment):
""" Home Assistant template environment. """
def is_safe_callable(self, obj):
return isinstance(obj, AllStates) or super().is_safe_callable(obj)
ENV = TemplateEnvironment()
ENV.filters['round'] = forgiving_round ENV.filters['round'] = forgiving_round
ENV.filters['multiply'] = multiply ENV.filters['multiply'] = multiply

View File

@ -101,6 +101,14 @@ class TestUtilTemplate(unittest.TestCase):
with self.assertRaises(TemplateError): with self.assertRaises(TemplateError):
template.render(self.hass, '{{ invalid_syntax') template.render(self.hass, '{{ invalid_syntax')
def test_if_state_exists(self):
self.hass.states.set('test.object', 'available')
self.assertEqual(
'exists',
template.render(
self.hass,
'{% if states.test.object %}exists{% else %}not exists{% endif %}'))
def test_is_state(self): def test_is_state(self):
self.hass.states.set('test.object', 'available') self.hass.states.set('test.object', 'available')
self.assertEqual( self.assertEqual(
@ -108,3 +116,12 @@ class TestUtilTemplate(unittest.TestCase):
template.render( template.render(
self.hass, self.hass,
'{% if is_state("test.object", "available") %}yes{% else %}no{% endif %}')) '{% if is_state("test.object", "available") %}yes{% else %}no{% endif %}'))
def test_states_function(self):
self.hass.states.set('test.object', 'available')
self.assertEqual(
'available',
template.render(self.hass, '{{ states("test.object") }}'))
self.assertEqual(
'unknown',
template.render(self.hass, '{{ states("test.object2") }}'))