user124114
user124114

Reputation: 8691

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?

Upvotes: 9

Views: 5664

Answers (2)

ascobol
ascobol

Reputation: 7706

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

Upvotes: 16

Giovanni Di Milia
Giovanni Di Milia

Reputation: 14041

According to the documentation you can't because that behavior is a feature: see here

What I would do is to write a custom filter that behaves more in a pythonic way and raises an KeyError in case.

Something that can be used more or less like:

jinja2.Template("Hello {{ a|myget('x') }}").render(a={})

Upvotes: 0

Related Questions