【发布时间】:2016-12-09 13:30:02
【问题描述】:
我有模型(事件),我想要有两种显示项目的方式的模板。 第一行必须包含两个具有特殊样式的项目 第二个和下一个必须包括三个,具有特殊样式
如何使用循环来做到这一点?
【问题讨论】:
标签: django loops templates frontend
我有模型(事件),我想要有两种显示项目的方式的模板。 第一行必须包含两个具有特殊样式的项目 第二个和下一个必须包括三个,具有特殊样式
如何使用循环来做到这一点?
【问题讨论】:
标签: django loops templates frontend
你可以像下面那样做
views.py
def view(request):
events = Event.objects.all()
l = []
for i in range(0,len(events), 5):
l.append((events[i:i+2], events[i+2:i+5]))
return render(request, "template.html", {"events": l})
模板.html
{% for two_items, three_items in events %}
<tr class="class1">
{% for item in two_items %}
<td> {{ item }}</td>
{% endfor %}
<tr>
<tr class="class2">
{% for item in three_items %}
<td> {{ item }}</td>
{% endfor %}
<tr>
{% endfor %}
【讨论】:
cycle 和 forloop 标签的组合将为您提供所需的输出: 例如:
{% for item in items %}
{% if forloop.counter < 3 %}
{% if forloop.first %}
<tr class="A">
{% endif %}
<td>{{ item }}</td>
{% endif %}
{% if forloop.counter == 3 %}
</tr>
{% endif %}
{% if forloop.counter >= 3 %}
{% cycle "<tr class='B'>" "" "" %}
<td>{{ item }}</td>
{% cycle "" "" "</tr>" %}
{% endif %}
{% endfor %}
【讨论】: