diff --git a/homeassistant/util/template.py b/homeassistant/util/template.py index b7fc3197e08..ad0fabdab53 100644 --- a/homeassistant/util/template.py +++ b/homeassistant/util/template.py @@ -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): diff --git a/tests/util/test_template.py b/tests/util/test_template.py index 16e1f8b6a04..ba354f3e7be 100644 --- a/tests/util/test_template.py +++ b/tests/util/test_template.py @@ -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')