【问题标题】:First row with two items second one and next with three第一行有两个项目第二个和下一个有三个
【发布时间】:2016-12-09 13:30:02
【问题描述】:

我有模型(事件),我想要有两种显示项目的方式的模板。 第一行必须包含两个具有特殊样式的项目 第二个和下一个必须包括三个,具有特殊样式

如何使用循环来做到这一点?

【问题讨论】:

    标签: django loops templates frontend


    【解决方案1】:

    你可以像下面那样做

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

    【讨论】:

      【解决方案2】:

      cycleforloop 标签的组合将为您提供所需的输出: 例如:

      {% 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 %}
      

      【讨论】:

        猜你喜欢
        • 2020-07-13
        • 2023-01-01
        • 2015-06-02
        • 2015-11-16
        • 2014-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多