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?
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With