2013-07-10 45 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 %}