我正在尝试从Django模板中访问数组的元素,但我收到“field * not found”错误。我的模板语法如下:
<h3>Data:</h3>
<table>
<thead>
<tr><th> Row[0] </th><th> Row[1] </th><th> Row[2] </th></tr>
</thead>
<tbody>
{% for row in info %}
<tr>
<td>{{ row.0 }}</td>
<td align = 'center'>{{ row.1 }}</td>
<td align = 'center'>{{ row.2 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
通过我的堆栈跟踪读取它看起来问题是模板引擎试图使用下标的下载版本来引用数组字段;这样:
{{ row.0 }}
被引用为row[u'0']
而不是row[0]
从而导致错误。
确切的错误是:Caught ValueError while rendering: field named 0 not found
它出现在:
current = context
try: # catch-all for silent variable failures
for bit in self.lookups:
try: # dictionary lookup
==> current = current[bit]
except (TypeError, AttributeError, KeyError):
try: # attribute lookup
current = getattr(current, bit)
except (TypeError, AttributeError):
try: # list-index lookup
current = current[int(bit)]
所以它没有达到尝试列表索引查找的程度。为什么会这样?
答案 0 :(得分:0)
您可以使用嵌套for循环而不是显式项索引:
{% for row in info %}
<tr>
{% for value in row %}
<td {% if forloop.counter > 0 %}align = 'center'{% endif %}> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
答案 1 :(得分:0)
{{row.0}}应该可行。如果没有 - 用你自己的逻辑写出模板标签:
@register.simple_tag
def get(l, i):
return l[int(i)]