有人知道如何避免模板重复吗?我用for循环尝试了一下,但没有成功。
<p>
Current:<br>
{% for event in states.current %}
<a href="{% url 'ambassadors:event' organizer=event.organizer.slug event=event.slug %}">{{ event.name }}</a>
{% endfor %}
</p>
<p>
Past:<br>
{% for event in states.past %}
<a href="{% url 'ambassadors:event' organizer=event.organizer.slug event=event.slug %}">{{ event.name }}</a>
{% endfor %}
</p>
答案 0 :(得分:0)
简单的解决方案:在视图中设置适当的上下文数据结构:
def yourview(request, ...):
# code here
context = {
# other stuff here
"states_data": [
# (label, events)
("Current", states.current()),
("Past", states.past())),
]
}
然后在您的模板中:
{% for label, events in states_data %}
<p>
{{ label }}
{% for event in events %}
<a href="{% url 'ambassadors:event' organizer=event.organizer.slug event=event.slug %}">{{ event.name }}</a>
{% endfor %}
</p>
{% endfor %}