Reputation: 10979
I have this super dumb code:
{% set count = 0 %}
{% for key in 'foo', 'bar': %}
{% for x in 'a', 'b': %}
{{count}}
{% set count = count + 1 %}
{% endfor %}
{% endfor %}
What I get is "0 1 0 1" instead of "0 1 2 3".
Why?!
Upvotes: 1
Views: 2599
Reputation: 533
I think this is cleaner:
{% set count = [] %}
{% for key in 'foo', 'bar': %}
{% for x in 'a', 'b': %}
{{count|length}}
{% set var = count.append(1) %}
{% endfor %}
{% endfor %}
Upvotes: 1
Reputation: 10648
Here is kind of a hacky solution (This is based off of this answer: Jinja2: Change the value of a variable inside a loop):
{% set count = {'value': 0} %}
{% for key in 'foo', 'bar': %}
{% for x in 'a', 'b': %}
{{count.value}}
{% if count.update({'value': (count.value + 1)}) %} {% endif %}
{% endfor %}
{% endfor %}
What is happening in your code is that set
is an assignment operator. Since you call set in the nested loop, the count in the nested loop is a different variable.
So to get around the issue, you can use a dict as shown in the answer I linked to.
Next, you need to do one more hack, which is to use an empty if statement to update the dict. You can't just do the following since it will lead to a syntax error in jinja:
{% count.update({'value': (count.value + 1)}) %}
Another option is to create your own jinja function, and then you can do something like this:
{% set count = {'value': 0} %}
{% for key in 'foo', 'bar': %}
{% for x in 'a', 'b': %}
{{count.value}}
{{ increment_count(count) }}
{% endfor %}
{% endfor %}
Here I created a function called increment_count
:
def increment_count(count):
count['value'] += 1
return ''
The count returns an empty string so we can don't have to use empty if statement. I usually use Flask with Jinja. With Flask you can add function using a context processor: http://flask.pocoo.org/docs/0.10/templating/#context-processors
Upvotes: 3
Reputation: 5354
I am not sure if this is Python. But it's tagged as pythonic question. If you write this function using Python. You will get the desired output.
count= 0
l=[]
for key in "foo", "bar":
for x in 'a','b':
l+=[count]
count+=1
print l
The output: [0, 1, 2, 3]
Upvotes: -3