【问题标题】:Total number of iteration for Django nested loopsDjango 嵌套循环的迭代总数
【发布时间】:2021-11-30 07:08:21
【问题描述】:

示例: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 %}

如何获取每次迭代的内部和外部for循环的总迭代次数?

期望的输出: 印度 1)孟买:19,000,000 美国 2)纽约:20,000,000 印度 3)加尔各答:15,000,000 美国 4)芝加哥:7,000,000 日本 5)东京:33,000,000

forloop.counter 和 forloop.counter0 只返回内部索引

【问题讨论】:

标签: django django-models django-rest-framework django-views django-templates


【解决方案1】:

您可以使用有序列表(<ol>)并跳过不应该编号的项目

<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>

【讨论】:

  • 那么已经在Python中添加了索引,做这种逻辑不属于模板。
猜你喜欢
  • 2011-05-20
  • 2014-10-22
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多