Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2: Change the value of a variable inside a loop

Tags:

python

jinja2

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?

like image 682
Shankar Cabus Avatar asked Feb 28 '12 17:02

Shankar Cabus


People also ask

Can I change the I value inside for loop?

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 assign a value to a variable in Jinja2?

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.

How do you make a loop in Jinja2?

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.


2 Answers

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)!
like image 189
Pashka Avatar answered Oct 23 '22 21:10

Pashka


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 %}
like image 73
Omer Avatar answered Oct 23 '22 20:10

Omer