我有一个列表,其中包含从我的视图返回的嵌套列表,例如 -
[[1, [1, 2, 3]], [2, [2, 3, 4]], [3, [3,4,5]]]
我想要这样的东西,它可以在python中运行 -
for obj in my_list:
for nested_obj in obj[1]:
print nested_obj
但是使用django模板系统,如果我尝试 -
{% for obj in data_list %}
<h2>{{obj.0}}</h2>
<p>
{{for nested_obj in obj.1}}
<h5>{{nested_obj}}</h5>
{{ endfor }}
</p>
{% endfor %}
我明白了 -
Could not parse the remainder: ' nested_obj in obj.1' from 'for nested_obj in obj.1'
这是为什么? 谢谢!
编辑 -
所以,这是愚蠢的 - 我写了{{for .... }}
而不是{% for ... %}
谢谢@allcaps
答案 0 :(得分:1)
{{ for x in ... }}
导致TemplateSyntaxError,应为{% for x in ... %}
。
python manage.py shell
from django.template import Template, Context
data_list = [[1, [1, 2, 3]], [2, [2, 3, 4]], [3, [3, 4, 5]]]
template = """
{% for obj in data_list %}
Obj {{obj.0}}
{% for nested_obj in obj.1 %}
Nested {{nested_obj}}
{% endfor %}
{% endfor %}
"""
t = Template(template)
c = Context({"data_list": data_list})
print t.render(c)
出:
Obj 1 Nested 1 Nested 2 Nested 3 Obj 2 Nested 2 Nested 3 Nested 4 Obj 3 Nested 3 Nested 4 Nested 5
答案 1 :(得分:0)
也许这有效......
data_list = [[1, [1, 2, 3]], [2, [2, 3, 4]], [3, [3,4,5]]]
{% for header, remainder in data_list %}
<h2>a</h2>
<p>
{{ for x in remainder }}
<h5>{{ x }}</h5>
{{ endfor }}
</p>
{% endfor %}