Ale*_*lex 17 django templates for-loop list django-templates
在我的Django 1.1.1应用程序中,我在视图中有一个函数,它向模板返回一系列数字和一系列项目列表,例如:
...
data=[[item1 , item2, item3], [item4, item5, item6], [item7, item8, item9]]
return render_to_response('page.html', {'data':data, 'cycle':range(0,len(data)-1])
Run Code Online (Sandbox Code Playgroud)
在模板内部我有一个外部for循环,其中还包含另一个循环以在输出中显示以这种方式包含内部数据列表
...
{% for page in cycle %}
...
< table >
{% for item in data.forloop.counter0 %}
< tr >< td >{{item.a}} < /td > < td > {{item.b}} ... < /td > < /tr >
...
< /table >
{% endfor %}
{% if not forloop.last %}
< div class="page_break_div" >
{% endif %}
{% endfor %}
...
Run Code Online (Sandbox Code Playgroud)
但是Django模板引擎不能将forloop.counter0值作为列表的索引(相反,如果我手动将数值作为索引).有没有办法让列表循环与外部forloop.counter0值一起使用?在此先感谢您的帮助 :)
Mar*_*ark 17
我以一种相当低效的方式解决了这个问题.阅读此代码时,请不要摔倒在计算机上.给定两个相同长度的列表,它将遍历第一个并从第二个打印相应的项目.
如果必须使用它,只能将它用于很少访问的模板,其中两个列表的长度都很小.理想情况下,重构模板的数据以完全避免此问题.
{% for list1item in list1 %}
{% for list2item in list2 %}
{% if forloop.counter == forloop.parentloop.counter %}
{{ list1item }} {{ list2item }}
{% endif %}
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
ste*_*anw 12
您不能将变量用于属性名称,字典键或列表索引.
也是range(0,len(data)-1]无效的python.它应该是range(len(data)).
你可能不需要cycle.也许你想要的是这个:
{% for itemlist in data %}
...
<table>
{% for item in itemlist %}
<tr>
<td>{{ item.a }}</td>
<td>{{ item.b }} ... </td>
</tr>
...
{% endfor %}
</table>
{% if not forloop.last %}
<div class="page_break_div">
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)