强制移动到django中模板for循环中的下一条记录

强制移动到django中模板for循环中的下一条记录,django,django-templates,Django,Django Templates,我有一个三列表(第1列和第3列将显示一个图像)。我用forloop循环模板中的对象列表 在循环中,我想强制forloop转到下一项,这样第3列中的项就是下一条记录。我在django文档中看不到类似“forloop.next”的内容 {% for item in object_list %}<tr> <td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" wid

我有一个三列表(第1列和第3列将显示一个图像)。我用forloop循环模板中的对象列表

在循环中,我想强制forloop转到下一项,这样第3列中的项就是下一条记录。我在django文档中看不到类似“forloop.next”的内容

{% for item in object_list %}<tr>
    <td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
    <td>&nbsp;</td>
    <td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
</tr>
{% endfor %}<tr>
{%用于对象列表%中的项]
{%endfor%}

实现这一点的最佳方法是什么?

您可以创建迭代器,它将在每次迭代中生成一对元素

差不多

from itertools import tee, izip, islice

iter1, iter2 = tee(object_list)
object_list = izip(islice(iter1, 0, None, 2), islice(iter2, 1, None, 2))

# if object_list == [1,2,3,4,5,6,7,8] then result will be iterator with data: [(1, 2), (3, 4), (5, 6), (7, 8)]
也可以在模板中执行以下操作:

{% for item in object_list %}
{% if forloop.counter0|divisibleby:2 %}
<tr>
<td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
<td>&nbsp;</td>
{% else %}
<td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
</tr>
{% endif %}
{% endfor %}
{%用于对象列表%中的项]
{%if-forloop.counter0 | divisibleby:2%}
{%else%}
{%endif%}
{%endfor%}
但要确保集合中甚至有元素,否则
将不会关闭