Django template skip line every two iteration

一曲冷凌霜 提交于 2019-12-23 04:54:34

问题


I have the following html structure:

<div class="row>
    <div class="box"></div>
    <div class="box"></div>
</div>

I am using pagination feature on Django to pass on 6 items per page.

How would I go about iterating over the paginator generated object list while wrapper each two box divs with row div?


回答1:


You can use the forloop.counter in the template

{% for obj in obj_list %}
    {% if forloop.counter0|divisibleby:2 %}
    <div class="row">
    {% endif %}
        <div class="box"></div>
        <div class="box"></div>
    {% if forloop.counter|divisibleby:2 %}
    </div>
    {% endif %}

{% else %}
    Nothing to show
{% endfor %}

and if there are odd number of elements in the list, then it would not have a trailing div. I will let you figure out that scenario by yourself. (it is pretty simple)

Documentation for the forloop.counter0 can be found here Documentation for divisibleby can be found here




回答2:


I agree with karthikr's solution, but it doesn't print the </div> if you have 3, 5 items...

You have to add a forloop.last to handle that case:

{% for obj in obj_list %}
    {% if forloop.counter0|divisibleby:2 %}
    <div class="row">
    {% endif %}
        <div class="box"></div>
        <div class="box"></div>
    {% if forloop.counter|divisibleby:2 or forloop.last %}
    </div>
    {% endif %}

{% else %}
    Nothing to show
{% endfor %}


来源:https://stackoverflow.com/questions/25695800/django-template-skip-line-every-two-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!