【问题标题】:Force move to next record within for loop in a template in django在 django 的模板中强制移动到 for 循环中的下一条记录
【发布时间】:2012-01-20 06:53:01
【问题描述】:

我有一个三列表(第 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>

最好的方法是什么?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    你可以制作迭代器,每次迭代都会产生一对元素。

    类似

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

    但请确保您的集合中有偶数元素,否则&lt;tr&gt; 不会被关闭。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 2021-10-17
      • 1970-01-01
      • 2015-03-21
      • 2010-11-09
      • 2019-05-23
      相关资源
      最近更新 更多