views:

76

answers:

2

I have two for loops, both alike in dignity. I'd like to have a counter incremented during each inner iteration.

For example, consider this template:

from jinja2 import Template

print Template("""
{% set count = 0 -%}
{% for i in 'a', 'b', 'c' -%}
  {% for j in 'x', 'y', 'z' -%}
    i={{i}}, j={{j}}, count={{count}}
    {% set count = count + 1 -%}
  {% endfor -%}
{% endfor -%}
""").render()

Shouldn't this print count=0 through count=8? Nope, it doesn't.

i=a, j=x, count=0
i=a, j=y, count=1
i=a, j=z, count=2
i=b, j=x, count=0
i=b, j=y, count=1
i=b, j=z, count=2
i=c, j=x, count=0
i=c, j=y, count=1
i=c, j=z, count=2

What gives?

Note: I can't simply save the outer loop variable to calculate the counter because, in my software, the number of inner iterations is variable.

+2  A: 

It does look like a bug, but how about moving some of that calculation outside the template?

from jinja2 import Template

outer_items = list(enumerate("a b c".split()))
inner_items = list(enumerate("x y z".split()))

print Template("""
{% for outer, i in outer_items -%}
  {% for inner, j in inner_items -%}
  {% set count = outer * num_outer + inner -%}
    i={{i}}, j={{j}}, count={{count}}
  {% endfor -%}
{% endfor -%}
""").render(outer_items=outer_items,
            inner_items=inner_items,
            num_outer=len(outer_items))

Output:

i=a, j=x, count=0
  i=a, j=y, count=1
  i=a, j=z, count=2
  i=b, j=x, count=3
  i=b, j=y, count=4
  i=b, j=z, count=5
  i=c, j=x, count=6
  i=c, j=y, count=7
  i=c, j=z, count=8
Ryan Ginstrom
This is a good idea, but I mentioned that I don't know the contents of the inner loop beforehand. See my answer....
a paid nerd
So you don't know it when you're in the Python code? Where is the inner loop coming from? But at any rate, I think a paid nerd's answer solves the problem.
Ryan Ginstrom
+2  A: 

With variable inner group sizes, this will work:

from jinja2 import Template

items = [
    ['foo', 'bar'],
    ['bax', 'quux', 'ketchup', 'mustard'],
    ['bacon', 'eggs'],
    ]

print Template("""
{% set counter = 0 -%}
{% for group in items -%}
  {% for item in group -%}
    item={{ item }}, count={{ counter + loop.index0 }}
  {% endfor -%}
  {% set counter = counter + group|length %}
{% endfor -%}
""").render(items=items)

...which prints:

item=foo, count=0
  item=bar, count=1

item=bax, count=2
  item=quux, count=3
  item=ketchup, count=4
  item=mustard, count=5

item=bacon, count=6
  item=eggs, count=7

I guess variables declared outside up more than one level of scope can't be assigned to or something.

a paid nerd