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 }}`.
This commit is contained in:
parent
c8add59ea5
commit
118f2f0bad
1 changed files with 9 additions and 1 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Reference in a new issue