How flexible is there in a Django loop?

I output a number of Django objects in the template:

{% for obj in list %}
    ...
{% endfor %}

But I would only like to bring out the first five of them, and then put the rest in a separate <DIV>.idea. The idea is that I can hide the other half until it is needed.

I am assuming something like this, but you need to limit duplicate elements:

{% for obj in list %}
    ...
{% endfor %}

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

Is it possible to do this only inside the template? This is presentation logic, so I would rather not pollute the view.

+3
source share
3 answers

You can 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>
+16
source

, , :

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

, , , , , , . , .

. "".

+7

, , forloop.counter if - -, <= 5, , > 5 (, 1-based - 0- , forloop.counter0).

+2

Source: https://habr.com/ru/post/1709956/


All Articles