Warm tip: This article is reproduced from serverfault.com, please click

python-在Django模板中使用带计数器的while循环

(python - Using while loop with counter in django template)

发布于 2020-11-28 12:38:54

我需要在模板的while循环中放置一个计数器。所以我做了:

<tbody> 
    {% with count=1 %}
    {% while count <={{orders_count}}: %}
        {% for order in orders %}
            <tr>
                <td style="width:5%;"></td>
                <td>{{count}}</td>
                <td>{{order.name}}</td>
            </tr>
            {% count+=1 %}
        {% endfor %}
    {% endwhile %}
    {% endwith %}
</tbody>

但最后我有以下错误:

Invalid block tag on line 216: 'while', expected 'endwith'. Did you forget to register or load this tag?
Questioner
M.J
Viewed
0
Willem Van Onsem 2020-11-28 20:51:06

while在这里不需要循环,只需使用|slice模板过滤器[Django-doc]即可

<tbody> 
    {% for order in orders|slice:orders_count %}
        <tr>
            <td style="width:5%;"></td>
            <td>{{ forloop.counter }}</td>
            <td>{{ order.name }}</td>
        </tr>
    {% endfor %}
</tbody>

但是,切片等,确实没有真正属于的模板通常,你可以在视图中执行此操作