I want to change the value of the variable declared outside the loop within a loop. But always changing, it keeps the initial value outside the loop.
{% set foo = False %}
{% for item in items %}
{% set foo = True %}
{% if foo %} Ok(1)! {% endif %}
{% endfor %}
{% if foo %} Ok(2)! {% endif %}
This renders:
Ok(1)!
So the only (bad) solution have found so far was this:
{% set foo = [] %}
{% for item in items %}
{% if foo.append(True) %} {% endif %}
{% if foo %} Ok(1)! {% endif %}
{% endfor %}
{% if foo %} Ok(2)! {% endif %}
This renders:
Ok(1)!
Ok(2)!
But, its is very ugly! Is there another more elegant solution?
Using While loop: We can't directly increase/decrease the iteration value inside the body of the for loop, we can use while loop for this purpose.
How do you set variables in Jinja? {{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.
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)!
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 %}
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