Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if given variable exist in jinja2 template?

Tags:

python

jinja2

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?

like image 740
Radosław Łazarz Avatar asked Dec 19 '12 16:12

Radosław Łazarz


People also ask

How do you check if a variable exists in Jinja?

There is a special value called undefined that represents values that do not exist. Depending on the configuration it will behave different. In order to check if a value is defined you can use the defined test: {{ myvariable is not defined }} will return true if the variable does not exist.

How are variables in Jinja2 templates specified?

Variables. Template variables are defined by the context dictionary passed to the template. You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too.


2 Answers

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.

like image 76
jeffknupp Avatar answered Sep 18 '22 05:09

jeffknupp


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"

like image 42
munk Avatar answered Sep 20 '22 05:09

munk