mirror of
https://github.com/home-assistant/core.git
synced 2025-04-23 16:57:53 +00:00
Add flexible error value for value template parsing
This commit is contained in:
parent
b1bf6a609e
commit
2b975c8620
@ -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):
|
||||
|
@ -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')
|
||||
|
Loading…
x
Reference in New Issue
Block a user