[Django]-How much flexibility is there in a Django for loop?

18👍

You could use slice:

{% for obj in list|slice:":5" %}
    ...
{% endfor %}

<a href="" onclick="unhide()">Show hidden</a>
<div id="hidden">
    {% for obj in list|slice:"5:" %}
        ...
    {% endfor %}
</div>

7👍

Struggling with template limitations can often be a sign that life might be simpler if you did more work in your view:

context = {
  'visible_list': mylist[:5],
  'hidden_list': mylist[5:]
}

I’m not saying this is neccesarily any better than the slice filter solution above but it’s often worth considering passing your templates a context object with everything set up nicely. It allows you to adapt more easily should the logic get even more complex later on.

Presentation logic sits quite nicely in a view. I don’t particularly see it as ‘pollution’.

2👍

Sure, for example you can do the loop twice and within it use forloop.counter in suitable if constructs — the first time to only do stuff when it’s <= 5, the second time only when it’s > 5 (remember it’s 1-based — if you want a 0-based one, use forloop.counter0 instead).

Leave a comment