【问题标题】:Django - Iterating over list in templateDjango - 迭代模板中的列表
【发布时间】:2021-10-28 21:07:17
【问题描述】:

目前正在尝试使用 Django 模板迭代列表。 我想要实现的是多行三列。当前的逻辑大约每三个卡片元素创建一行。

创建每行三列的最佳方法是什么?

{% extends "stockwatcher/base.html" %}
{% block content %}

<div class="container">
  {% for stock in stocks %}
    {% if forloop.counter0 == 0 or forloop.counter0|divisibleby:3 %}
    <div class="row">
    {% endif %}
    <div class="col-sm">
      <div class="card text-white bg-info mb-3" style="max-width: 18rem;">
        <div class="card-header">{{stock.transaction_date}}</div>
        <div class="card-body">
          <h5 class="card-title">{{ stock.id }} {{stock.ticker}} </h5>
          <p class="card-text">{{stock.senator}} - {{stock.type}}</p>
        </div>
      </div>
    </div>
    {% if forloop.counter0 == 0 or forloop.counter0|divisibleby:3 %}
    </div> 
    {% endif %}
  {% endfor %}
</div>

{% endblock content %}

【问题讨论】:

    标签: python html css django templates


    【解决方案1】:

    您应该在 for 循环之外使用 row div,引导类将为您处理其余部分。你也可以使用{% empty %}标签来处理空列表。

    {% extends "stockwatcher/base.html" %}
    {% block content %}
    
    <div class="container">
        <div class="row">
        {% for stock in stocks %}
        <div class="col-sm">
          <div class="card text-white bg-info mb-3" style="max-width: 18rem;">
            <div class="card-header">{{stock.transaction_date}}</div>
            <div class="card-body">
              <h5 class="card-title">{{ stock.id }} {{stock.ticker}} </h5>
              <p class="card-text">{{stock.senator}} - {{stock.type}}</p>
            </div>
          </div>
        </div>
        {% empty %}
            No items
        {% endfor %}
        </div>
    </div>
    
    {% endblock content %}
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2014-09-06
      • 2014-05-14
      • 1970-01-01
      相关资源
      最近更新 更多