[Answered ]-How can I get index of list in django template

1👍

What you are trying to achieve is, as far as I know, not possible within templates.

To make sure we are on the same page I will show the code in python that you want to translate to "django-template-syntax"

r = range(3)
list1 = ["ape", "whale", "giraffe"]
list2 = ["brown", "blue", "yellow"]
for idx in r:
    print(list1[idx], list2[idx]

Solution 1:
Do it without a for-loop and access every item. Might be very tedious but still an option.

<table>
  <tr>
    <td> {{ item2.1 }} </td>
    <td> {{ item3.1 }} </td>
  </tr>
  <tr>
    <td> {{ item2.2 }} </td>
    <td> {{ item3.2 }} </td>
  </tr>
</table>

Solution 2:
As I said iterating over two lists simultaneously like shown in my python example is not possible within the templating-syntax. You need to zip those lists inside your views:
views.py:

item2 =  ['one', 'two','three','four', 'five']
item3 = ['six', 'seven','eight','nine','ten']
context={'item0': region.objects.all(),
         'item1': [1,2,3,4,5,6,7,8,9,10],
         'item23': zip(item2, item3)
         'item4': "test",
         'item5': 5,
         'item6': range(5),
         }

Then in your template you do it like this:
temp.html:

<table>
{% for i2, i3 in item23 %}
<tr>
  <td> {{ i2 }} </td> 
  <td> {{ i3 }} </td> 
</tr>
{% endfor %}
</table>

If your question’s target is just how to display the index of the loop you can do like this:
temp.html:

<table>
{% for i2, i3 in item23 %}
<tr>
  <td> {{ forloop.counter0 }} </td>
  <td> {{ i2 }} </td> 
  <td> {{ i3 }} </td> 
</tr>
{% endfor %}
</table>

You can not use that forloop counter as an index for other lists similar to my python example above.

Leave a comment