且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django模板每两次迭代跳过一行

更新时间:2023-02-05 19:30:28

您可以使用 forloop.counter

{% 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 %}

如果列表中元素的数量为奇数,则它将没有尾随的 div 。我会让你自己弄清楚这种情况。 (非常简单)

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)

forloop.counter0 可以在此处找到
divisibleby 可以在此处找到

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