Add value renderer helper method

This commit is contained in:
Paulus Schoutsen 2015-12-10 21:38:35 -08:00
parent 7acef84aad
commit d55fda28c2
2 changed files with 27 additions and 0 deletions

View file

@ -5,9 +5,24 @@ homeassistant.util.template
Template utility methods for rendering strings with HA data. Template utility methods for rendering strings with HA data.
""" """
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
import json
from jinja2.sandbox import ImmutableSandboxedEnvironment from jinja2.sandbox import ImmutableSandboxedEnvironment
def render_with_possible_json_value(hass, template, value):
""" Renders template with value exposed.
If valid JSON will expose value_json too. """
variables = {
'value': value
}
try:
variables['value_json'] = json.loads(value)
except ValueError:
pass
return render(hass, template, variables)
def render(hass, template, variables=None, **kwargs): def render(hass, template, variables=None, **kwargs):
""" Render given template. """ """ Render given template. """
if variables is not None: if variables is not None:

View file

@ -72,3 +72,15 @@ class TestUtilTemplate(unittest.TestCase):
def test_passing_vars_as_vars(self): def test_passing_vars_as_vars(self):
self.assertEqual( self.assertEqual(
'127', template.render(self.hass, '{{ hello }}', {'hello': 127})) '127', template.render(self.hass, '{{ hello }}', {'hello': 127}))
def test_render_with_possible_json_value_with_valid_json(self):
self.assertEqual(
'world',
template.render_with_possible_json_value(
self.hass, '{{ value_json.hello }}', '{"hello": "world"}'))
def test_render_with_possible_json_value_with_invalid_json(self):
self.assertEqual(
'',
template.render_with_possible_json_value(
self.hass, '{{ value_json }}', '{ I AM NOT JSON }'))