Raise exception for undefined attributes in jinja2

I need the following to throw an exception:

jinja2.Template("Hello {{ ax }}").render(a={}) 

Jinja2 silently returns an empty string for ax , so this displays as "Hello".

How to make jinja2 throw an exception from undefined attributes?

+6
source share
2 answers
 from jinja2 import Template, StrictUndefined print Template("Hello {{ ax }}", undefined=StrictUndefined).render(a={}) 

This will throw an exception:

 File "<template>", line 1, in top-level template code jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'x' 

If you set the value for ax, then it will work as intended:

 print Template("Hello {{ ax }}", undefined=StrictUndefined).render(a={'x':42}) 

will print:

 Hello 42 
+7
source

According to the documentation you cannot, because this behavior is a feature: see here

What I would do is write a custom filter that will behave in a more pythonic way in the event of a KeyError .

Something that can be used more or less:

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

Source: https://habr.com/ru/post/948584/


All Articles