Django / DRY:避免在模板中重复

时间:2018-07-31 09:49:56

标签: django

有人知道如何避免模板重复吗?我用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>

1 个答案:

答案 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 %}