Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise an exception for undefined attributes in jinja2

Tags:

python

jinja2

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?

like image 736
user124114 Avatar asked Jul 02 '13 20:07

user124114


1 Answers

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
like image 80
ascobol Avatar answered Oct 24 '22 20:10

ascobol