如何在Django模板中获取组中对象的“总体”计数器?

lp0sw83n  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(147)

我使用Django的regroup template tag来分组一系列对象。假设这些是对象:

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

字符串
在我的模板中,我将它们分组如下:

{% regroup cities by country as country_list %}

<ul>
{% for country in country_list %}
    <li>{{ country.grouper }}
    <ul>
        {% for city in country.list %}
          <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>


这导致

India
    Mumbai: 19,000,000
    Calcutta: 15,000,000
USA
    New York: 20,000,000
    Chicago: 7,000,000
Japan
    Tokyo: 33,000,000


我想为每个对象显示一个“总体”索引,因此它看起来像这样:

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


我并不要求HTML解决方案;我的用例是一系列分组问题,我想添加一个问题计数器。
有没有一种方法可以在模板中实现这一点,或者我应该在我的视图中编写必要的代码?

mzsu5hc0

mzsu5hc01#

我认为你需要在你的视图中添加索引,Django有意限制其模板语言中的功能,以阻止直接在模板中包含广泛的逻辑。我建议通过以下建议的方法来解决这个问题:

# views.py
from django.shortcuts import render

def your_view(request):
    cities = [
        {"name": "Mumbai", "population": "19,000,000", "country": "India"},
        {"name": "Calcutta", "population": "15,000,000", "country": "India"},
        {"name": "New York", "population": "20,000,000", "country": "USA"},
        {"name": "Chicago", "population": "7,000,000", "country": "USA"},
        {"name": "Tokyo", "population": "33,000,000", "country": "Japan"},
    ]

    # Add an index to each city
    for index, city in enumerate(cities, start=1):
        city['index'] = index

    return render(request, 'your_template.html', {'cities': cities})

字符串
然后在你的模板中,你可以使用index属性:

{% regroup cities by country as country_list %}

<ul>
    {% for country in country_list %}
        <li>{{ country.grouper }}
        <ul>
            {% for city in country.list %}
                {% with counter=counter|add:1 %}
                 <li>{{ city.index }}: {{ city.name }}: {{ city.population }}</li>
                {% endwith %}
            {% endfor %}
        </ul>
        </li>
    {% endfor %}
</ul>

相关问题