brs*_*gic 2 django templates for-loop
我尝试在Django tempalte中实现一个forloop,每个周期迭代两个项目
{% for c in cList%}
<ul class="ListTable">
<li>
{{ c1.name }}
</li>
<li>
{{ c2.name }}
</li>
</ul>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我知道我的代码不是一种正确的方法,但我无论如何都找不到.我真的很感激任何建议
谢谢
如果你可以控制列表结构cList,为什么不把它作为2个元素的元组列表或2个元素的列表列表,如
#in the view
cList = [(ob1, ob2),
(ob3, ob4)]
Run Code Online (Sandbox Code Playgroud)
和模板中的
{% for c1, c2 in cList %}
<ul class="ListTable">
<li>
{{ c1.name }}
</li>
<li>
{{ c2.name }}
</li>
</ul>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
您也可以使用该zip函数来促进cList的创建,或者定义一个从对象列表中创建这种结构的函数,例如
def pack(_list):
new_list = zip(_list[::2], _list[1::2])
if len(_list) % 2:
new_list.append((_list[-1], None))
return new_list
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3306 次 |
| 最近记录: |