Jinja2: Change the value of a variable inside a loop
as mentioned in the documentation:
Please note that assignments in loops will be cleared at the end of the iteration and cannot outlive the loop scope.
but as of version 2.10 you can use namespaces:
{% set ns = namespace(foo=false) %}
{% for item in items %}
{% set ns.foo = True %}
{% if ns.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if ns.foo %} Ok(2)! {% endif %}
Try also dictionary-based approach. It seems to be less ugly.
{% set vars = {'foo': False} %}
{% for item in items %}
{% if vars.update({'foo': True}) %} {% endif %}
{% if vars.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if vars.foo %} Ok(2)! {% endif %}
This also renders:
Ok(1)!
Ok(2)!