From d55fda28c235570f330b0cb1253b62aaeebd69a0 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen <paulus@paulusschoutsen.nl> Date: Thu, 10 Dec 2015 21:38:35 -0800 Subject: [PATCH] Add value renderer helper method --- homeassistant/util/template.py | 15 +++++++++++++++ tests/util/test_template.py | 12 ++++++++++++ 2 files changed, 27 insertions(+) diff --git a/homeassistant/util/template.py b/homeassistant/util/template.py index 37eed7ad3f5..107532db776 100644 --- a/homeassistant/util/template.py +++ b/homeassistant/util/template.py @@ -5,9 +5,24 @@ homeassistant.util.template Template utility methods for rendering strings with HA data. """ # pylint: disable=too-few-public-methods +import json 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): """ Render given template. """ if variables is not None: diff --git a/tests/util/test_template.py b/tests/util/test_template.py index e85ed6dbba6..5c1dfff1f85 100644 --- a/tests/util/test_template.py +++ b/tests/util/test_template.py @@ -72,3 +72,15 @@ class TestUtilTemplate(unittest.TestCase): def test_passing_vars_as_vars(self): self.assertEqual( '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 }')) -- GitLab