I need the following to raise an exception:
jinja2.Template("Hello {{ a.x }}").render(a={})
Jinja2 silently returns an empty string for a.x
, so this renders as "Hello ".
How do I make jinja2 raise an exception on undefined attributes?
from jinja2 import Template, StrictUndefined
print Template("Hello {{ a.x }}", undefined=StrictUndefined).render(a={})
This will raise an exception:
File "<template>", line 1, in top-level template code
jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'x'
If you set a value for a.x then it will work as intended:
print Template("Hello {{ a.x }}", undefined=StrictUndefined).render(a={'x':42})
will print:
Hello 42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With