21

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?

4
  • 2
    Do you want to check for the variable before you render the template or in the template? Commented Dec 19, 2012 at 16:29
  • 2
    Before rendering! I need to check whether the rendering effect would make any sense... Commented Dec 24, 2012 at 3:06
  • 2
    So you want to check that the variable x is actually referenced in the template? Commented Dec 24, 2012 at 5:07
  • 2
    That is exactly what I want. Commented Dec 24, 2012 at 14:02

3 Answers 3

45

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.

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

1 Comment

Not exactly what I meant - I need to check whether the {{ variable }} fragment exists in template text or not.
1

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"

Comments

-4

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.

1 Comment

You brought bad news for me. Could you please provide any suggestions for such parsing? Jinja2 probably parse it anyway, I wonder whether it is possible to gain access to effects of this process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.