Raise an exception for undefined attributes in 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?

Best answer

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