2011-12-14 19 views
2

我有一個三列表(列1 & 3將顯示圖像)。我使用forloop循環遍歷模板中的對象列表。強制移動到django模板中的for循環內的下一條記錄

在循環內,我想迫使forloop轉到下一個項目,所以第三列中的項目是下一個記錄。我在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> 

完成此操作的最佳方法是什麼?

回答

2

您可以製作迭代器,它將在每次迭代中產生一對元素。

喜歡的東西

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

但要確保有偶數元素在你的設置,或者<tr>不會被關閉。

+0

謝謝。正是我需要的。 – zio 2011-12-14 21:48:08