2013-07-10 108 views
3

我有一個列表說列表[A] [B]長度10 的我想從列表打印[0] [B]到列表[10] [B]和使用它jinja2模板。取列表元素

{% for i in test %} 
<p> {{test[i][0]}} </p> 
{% endfor %} 

拋出錯誤:

UndefinedError: list object has no element 

回答

7

你實際上得到的元素淘汰之列,當你迭代它,而不是指標值:

{% for row in test %} 
    {# Note that we subscript `row` directly, 
    (rather than attempting to index `test` with `row`) #} 
    <p>{{ row[0] }}</p> 
{% endfor %} 
+0

乾杯!這個竅門! 。我想知道爲什麼這些東西沒有在文檔中提到。還是提到它,我沒有注意到它? –

+2

@ChandanGupta - 在這種情況下,行爲是由Python本身共享的,所以不會令人驚訝(因此,除了在文檔中提到'for',它「循環遍歷每個項目序列「 - 在Python *很多*的東西是可迭代的)。 :-) –

5

如果你想確保總是有第一個10:

{% for test in tests[0:10] %} 
<p> {{ test[1] }} </p> 
{% endfor %}