Radosław Łazarz
Radosław Łazarz

Reputation: 968

How to check if given variable exist in jinja2 template?

Let's say, I created a template object (f.e. using environment.from_string(template_path)). Is it possible to check whether given variable name exist in created template?

I would like to know, if

template.render(x="text for x")

would have any effect (if something would be actually replaced by "text for x" or not). How to check if variable x exist?

Upvotes: 20

Views: 34693

Answers (3)

jeffknupp
jeffknupp

Reputation: 6284

From the documentation:

defined(value)

Return true if the variable is defined:

{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}
See the default() filter for a simple way to set undefined variables.

EDIT: It seems you want to know if a value passed in to the rendering context. In that case you can use jinja2.meta.find_undeclared_variables, which will return you a list of all variables used in the templates to be evaluated.

Upvotes: 44

munk
munk

Reputation: 12983

I'm not sure if this is the best way, or if it will work in all cases, but I'll assume you have the template text in a string, either because you've created it with a string or your program has read the source template into a string.

I would use the regular expression library, re

>>> import re
>>> template = "{% block body %} This is x.foo: {{ x.foo }} {% endblock %}"
>>> expr = "\{\{.*x.*\}\}"
>>> result = re.search(expr, template)
>>> try: 
>>>     print result.group(0)
>>> except IndexError:
>>>     print "Variable not used"

The result will be:

'{{ x.foo }}'

or throw the exception I caught:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: no such group

which will print "Variable not used"

Upvotes: 1

djc
djc

Reputation: 11731

You can't do that.

I suppose you could parse the template and then walk the AST to see if there are references, but that would be somewhat complicated code.

Upvotes: -4

Related Questions