1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but I think forloop.counter is true.
Does pattern |slice:orders_count make more resources(RAM/CPU) in comparison with the state which we don't type it?
@M.J: not significantly no. But what is order_count? If it is just the number of items in orders, then you should not pass it to the template anyway.
1

You can try this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.