0

Example: django doc

cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

{% regroup cities by country as country_list %}

{% for country, local_cities in country_list %}
    {% for city in local_cities %}
       {{total_number_of_iteration_till_now}} {{ city.name }}: {{ city.population }}
    {% endfor %}
{% endfor %}

How do I get the total iteration number of both inner and outer for loop for each iteration?

Desired output:

India
1)Mumbai: 19,000,000
USA
2)New York: 20,000,000
India
3)Calcutta: 15,000,000
USA
4)Chicago: 7,000,000
Japan
5)Tokyo: 33,000,000

forloop.counter and forloop.counter0 return only inner index

djvg
  • 11,722
  • 5
  • 72
  • 103
panos
  • 328
  • 1
  • 4
  • 16
  • Does this answer your question? [How to access outermost forloop.counter with nested for loops in Django templates?](https://stackoverflow.com/questions/2376511/how-to-access-outermost-forloop-counter-with-nested-for-loops-in-django-template) – Wouter Oct 11 '21 at 14:22
  • What's the goal you're aiming at? Maybe there's a better way how to achieve that... – yedpodtrzitko Oct 11 '21 at 14:28
  • Im aiming at getting the total number of iteration for each iteration to visualise it together with each city(in this case) – panos Oct 11 '21 at 14:30
  • 1
    similar: https://stackoverflow.com/a/74094611 – djvg Oct 17 '22 at 08:45

1 Answers1

1

You can use ordered list (<ol>) and skip the items which shouldnt be numbered

<ol>
{% for country, local_cities in country_list %}
    {# this one wont be numbered #}
    <li style="list-style-type: none">{{ country }}</li>
        {% for city in local_cities %}
          <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    </li>
{% endfor %}
</ol>
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42