From 118f2f0badc77881bb28350479d8732fec615cca Mon Sep 17 00:00:00 2001 From: Jan Harkes Date: Fri, 14 Oct 2016 11:16:30 -0400 Subject: [PATCH] Use a filter to fail rendering undefined variables Instead of globally using StrictUndefined, introduce a filter that will trigger a render failure on undefined variables. Use as `{{ value_json.someval | is_defined }}`. --- homeassistant/helpers/template.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index c67f4e62665..2a72fc1a088 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -387,6 +387,13 @@ def timestamp_utc(value): return value +def fail_when_undefined(value): + """Filter to force a failure when the value is undefined.""" + if isinstance(value, jinja2.Undefined): + value() + return value + + def forgiving_float(value): """Try to convert value to a float.""" try: @@ -402,12 +409,13 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): """Test if callback is safe.""" return isinstance(obj, AllStates) or super().is_safe_callable(obj) -ENV = TemplateEnvironment(undefined=jinja2.StrictUndefined) +ENV = TemplateEnvironment() ENV.filters['round'] = forgiving_round ENV.filters['multiply'] = multiply ENV.filters['timestamp_custom'] = timestamp_custom ENV.filters['timestamp_local'] = timestamp_local ENV.filters['timestamp_utc'] = timestamp_utc +ENV.filters['is_defined'] = fail_when_undefined ENV.globals['float'] = forgiving_float ENV.globals['now'] = dt_util.now ENV.globals['utcnow'] = dt_util.utcnow