2

Considering

<ul>
{% for l in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] %}
{% for i in l %}
<li>
...
</li>
{% endfor %}
{% endfor %}
</ul>

in a Django template, what should I replace ... with to get

1
2
3
4
5
6
7
8
9

i.e. how can I get a counter for a nest for loop where the lenght of the elements in the external loop aren't always the same?

Update

<ul>
{% for l in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] %}
{% for i in l %}
<li>
  {{forloop.counter}}
</li>
{% endfor %}
{% endfor %}
</ul>

gives

1
2
3
1
2
1
2
3
4

and

<ul>
{% for l in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] %}
{% for i in l %}
<li>
  {{forloop.parentloop.counter}}
</li>
{% endfor %}
{% endfor %}
</ul>

gives

1
1
1
2
2
3
3
3
3
Raniere Silva
  • 2,527
  • 1
  • 18
  • 34
  • similar: https://stackoverflow.com/a/74094611 – djvg Oct 17 '22 at 08:46
  • Does this answer your question? [Django template counter in nested loops](https://stackoverflow.com/questions/13870890/django-template-counter-in-nested-loops) – djvg Oct 17 '22 at 09:37

1 Answers1

1

For the inner loop, you can use {{ forloop.counter }}. Meanwhile, for the outer loop, you can use {{ forloop.parentloop.counter }}.

Update

Have you tried doing {{ forloop.parentloop.counter|add:forloop.counter }}?

Source

Rod Xavier
  • 3,983
  • 1
  • 29
  • 41
  • Thanks @rod-xavier. Unfortunately `forloop.counter` and `forloop.parentloop.counter` don't solve the problem alone and since the elements of the external list don't have the same size I couldn't think a a simple algebric operation to compute the counter. – Raniere Silva Aug 05 '15 at 13:27
  • You can either merge together your lists in a view and pass that to the template, or write a simple tag to add the two indices: https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#simple-tags – bwarren2 Aug 05 '15 at 14:54
  • This does *not* work. For the OP's example, it yields: `2, 3, 4, 3, 4, 4, 5, 6, 7`. – djvg Oct 17 '22 at 08:54