Add flexible error value for value template parsing

This commit is contained in:
Paulus Schoutsen 2015-12-12 10:35:15 -08:00
parent b1bf6a609e
commit 2b975c8620
2 changed files with 16 additions and 2 deletions

View File

@ -12,9 +12,11 @@ from jinja2.sandbox import ImmutableSandboxedEnvironment
from homeassistant.exceptions import TemplateError
_LOGGER = logging.getLogger(__name__)
_SENTINEL = object()
def render_with_possible_json_value(hass, template, value):
def render_with_possible_json_value(hass, template, value,
error_value=_SENTINEL):
""" Renders template with value exposed.
If valid JSON will expose value_json too. """
variables = {
@ -29,7 +31,7 @@ def render_with_possible_json_value(hass, template, value):
return render(hass, template, variables)
except TemplateError:
_LOGGER.exception('Error parsing value')
return value
return value if error_value is _SENTINEL else error_value
def render(hass, template, variables=None, **kwargs):

View File

@ -85,6 +85,18 @@ class TestUtilTemplate(unittest.TestCase):
template.render_with_possible_json_value(
self.hass, '{{ value_json }}', '{ I AM NOT JSON }'))
def test_render_with_possible_json_value_with_template_error(self):
self.assertEqual(
'hello',
template.render_with_possible_json_value(
self.hass, '{{ value_json', 'hello'))
def test_render_with_possible_json_value_with_template_error_error_value(self):
self.assertEqual(
'-',
template.render_with_possible_json_value(
self.hass, '{{ value_json', 'hello', '-'))
def test_raise_exception_on_error(self):
with self.assertRaises(TemplateError):
template.render(self.hass, '{{ invalid_syntax')