53

Is there a method for jinja2 to raise an exception when we pass a variable that is not present in the template?

PS: This is different(or opposite) from raising an exception when a variable is present in the template but it is not passed. For this I use "undefined=StrictUndefined"

3 Answers 3

53

When you load your jinja2.Environment, set the 'undefined' parameter to 'jinja2.StrictUndefined', e.g.:

env = jinja2.Environment(loader=<someloader>, undefined=jinja2.StrictUndefined) 

You can catch and examine the render exception to see what was missing

EDIT It would help if I read your full question. :)

Sign up to request clarification or add additional context in comments.

2 Comments

Not an answer to the OP but just what I was looking for (and what most users are looking for, judging by the upvotes).
came here to upvote the wrong answer because it was my right answer
15

Maybe this could help you https://jinja.palletsprojects.com/en/2.11.x/api/#the-meta-api

>>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) set(['bar']) 

Comments

7

You can also do that:

from jinja2 import Template, StrictUndefined Template('name: {{ name }} , city: {{ city }}',undefined=StrictUndefined).render(**{"name":"foo","city":"bar"}) 

1 Comment

Excellent. Complements the Environment response. We use the one to discover the tokens but the other to actually render the content.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.