Can a Jinja variable's scope extend beyond in an inner block?
One way around this limitation is to enable the "do" expression-statement extension and use an array instead of boolean:
{% set exists = [] %}
{% for i in range(5) %}
{% if True %}
{% do exists.append(1) %}
{% endif %}
{% endfor %}
{% if exists %}
<!-- exists is true -->
{% endif %}
To enable Jinja's "do" expression-statement extension: e = jinja2.Environment(extensions=["jinja2.ext.do",])
Answer to a related question: I wanted to have a global counter of the number of times I entered a certain if-block in the template, and ended up with the below.
At the top of the template:
{% set counter = ['1'] %}
In the if-block I want to count:
{% if counter.append('1') %}{% endif %}
When displaying the count:
{{ counter|length }}
The string '1'
can be replaced with any string or digit, I believe. It is still a hack, but not a very large one.
Update 2018
As of Jinja 2.10 (8th Nov 2017) there is a namespace()
object to address this particular problem. See the official Assignments documentation for more details and an example; the class
documentation then illustrates how to assign several values to a namespace.