获取多个for循环中的迭代总数:django模板

问题描述 投票:0回答:1

我正在使用 django 开发一个项目 我有 2 个班级和学生列表 我需要迭代这些并使用 django 模板打印 s.no 、 class.name 和 class.student.name

代码片段看起来像这样:

            {% for class in classes %}
            {% for student in class.students %}
            <tr>
                <td>#{{ count }}</td>
                <td>{{ student.name }}</td>
                <td>{{ class.name }}</td>
            </tr>
            {% endfor %}
            {% endfor %}

我无法获得正确的计数,因为我们有 for 循环计数器的父循环计数器,但我需要总迭代的计数

我尝试过类似的事情

            {% with count=0 %}
            {% for class in classes %}
            {% for student in class.students %}
            {% with count=count|add:1 %}
            <tr>
                <td>#{{ count }}</td>
                <td>{{ student.name }}</td>
                <td>{{ class.name }}</td>
            </tr>
            {% endwith %}
            {% endwith %}
            {% endfor %}
            {% endfor %}

但这总是将计数设为 1

改变for循环的位置也不起作用。 我们有办法解决这个问题吗?

问候

python python-3.x django django-rest-framework django-templates
1个回答
0
投票

count
变量的初始化移到外循环之外。试试这个:

{% with count=0 %}

  {% for class in classes %}

    {% for student in class.students %}

      {% with count=count|add:1 %}

        <tr>

          <td>#{{ count }}</td>

          <td>{{ student.name }}</td>

          <td>{{ class.name }}</td>

        </tr>

      {% endwith %}

    {% endfor %}

  {% endfor%}

{% endwith %}
© www.soinside.com 2019 - 2024. All rights reserved.