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

Using while loop with counter in django template

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

I need to put a counter in while loop in template. So I did:

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

But finaly I have the following error:

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

You do not need a while loop here, you can simply make use of the |slice template filter [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>

But slicing, etc. does not really belong in the template. You normally do that in the view.