Add value renderer helper method
parent
7acef84aad
commit
d55fda28c2
|
@ -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:
|
||||
|
|
|
@ -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 }'))
|
||||
|
|
Loading…
Reference in New Issue