2011-01-19 188 views
9

我將兩個列表傳遞給模板。通常情況下,如果我是遍歷列表,我會做這樣的事情Django計數器循環索引列表

{% for i in list %} 

但我有兩個列表,我需要並行訪問,即。一個列表中的第n個項目對應於另一個列表中的第n個項目。我的想法是使用forloop.counter0遍歷一個列表並訪問另一個列表中的項目,但我無法弄清楚它的工作原理。

謝謝

回答

13

你不行。最簡單的方法是預處理你在zipped list數據,這樣

在你看來

x = [1, 2, 3] 
y = [4, 5, 6] 
zipped = zip(x, y) 

然後在你的模板:

{% for x, y in zipped %} 
    {{ x }} - {{ y }} 
{% endfor %} 
+0

您認爲這是比使用multifor更好的解決方案嗎?我當然喜歡這是一個更簡單的模板 – JPC 2011-01-19 04:05:35

0

不認爲你可以這樣做。在將對齊的數據結構傳遞給您的模板之前,您需要一個模板標記,或者更好的方式來對齊視圖邏輯中的列表。

5

聽起來你找我django-multiforloop。自述:

渲染這個模板

{% load multifor %} 
{% for x in x_list; y in y_list %} 
    {{ x }}:{{ y }} 
{% endfor %} 

與此背景下

context = { 
    "x_list": ('one', 1, 'carrot'), 
    "y_list": ('two', 2, 'orange') 
} 

將輸出

one:two 
1:2 
carrot:orange 
6

我最後不得不這樣做:

{% for x in x_list %} 
    {% for y in y_list %} 
    {% if forloop.counter == forloop.parentloop.counter %} 
     Do Something 
    {% endif %} 
    {% endfor %} 
{% endfor %} 
+0

我認爲這是一個'O(n^2)`解決方案,當你可以在'O(n)`中完成時。 – Pant 2017-06-26 16:44:32

9

要使用一個for循環計數器我編寫了以下非常簡單的過濾器訪問迭代:

from django import template 

register = template.Library() 

@register.filter 
def index(sequence, position): 
    return sequence[position] 

,然後我可以在我的模板,用它作爲(別忘了加載它):

{% for item in iterable1 %} 
    {{ iterable2|index:forloop.counter0 }} 
{% endfor %} 

希望這可以幫助別人!

+0

這雖然採取了一些額外的步驟來實現,但它允許`forloop.counter0`應該爲for循環提供變量。我將return語句改爲:`return sequence [position]`以滿足我的需要。 – Flash 2015-06-04 19:05:08