首页 > 解决方案 > Django/Bootstrap - 如何限制每行的块?

问题描述

我有一个页面,其中包含每个项目的引导卡,例如

{% for item in item %} 创建一张包含一些内容的卡片....

如何限制每行创建的卡片数量,直到它跳到它下面的行?

 <div class = 'card-group'>
{% for plant in plant%}
{% if plant.available%}
<div class="card text-white bg-dark mb-3" style=''>
  <img style='height: auto; max-width: 100%;' src="{{plant.thumbnail}}" alt="...">
  <div class="container">
    <h4 style='color:white;' class="card-title"><b>{{plant.name |title}}</b></h4>
    <p style='font-size: 20px'>Soil: {{plant.soil |title}}</p>
    <p style='font-size: 20px'>Price per unit: £{{plant.price |title}}</p>
  </div>
  <div class='button-section'>
  <button class="order-button"><a href=''>Order Online</a></button>
  </div>
</div>

{% endif %}
{% endfor %}
</div>

这是目前应用的css

.card {
    margin: 10px;
    display: flex;
}

.card-group {
    justify-content: space-evenly;
}

.card-title {
    font-size: 25px;
    font-weight: bold;
    margin-top: 10px;
}

.card-text,
.card-title {
    color: rgb(255, 255, 255);
}

.card-body {
    text-align: left;
}

.card-button {
    background-color: transparent;
    border: 3px solid #ff7505;
    color: rgb(255, 254, 254);
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 10px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    border-radius: 10px;
}

.card-button:hover {
    background-color: #f75c02;
    color: #000000;
    text-decoration: none;
}

我只想每行显示 4 个对象,然后跳到下一行,依此类推...

标签: htmlcssdjangobootstrap-4

解决方案


您可以使用forloop.counter和模板标签divisibleby。然后代码可以是这样的:

{% for item in items %}

  {% if forloop.counter0|divisibleby:"4" %}
    <div class="row">
  {% endif %}

  {% if forloop.counter0|divisibleby:"4" %}
    </div>
  {% endif %}

{% endfor %}

或者您可以在视图中实现该逻辑。可以看起来像这样:

rows = []
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]  # Item.objects.all() etc.
per_row = 4

i = 0
while True:
    row_items = items[i * per_row : (i + 1) * per_row]
    if not row_items:
        break
    rows.append(row_items)
    i += 1
print(rows)

当您运行有关输出的示例时,[[1, 2, 3, 4], [5, 6, 7, 8], [9]]您有嵌套列表,因此您必须在模板中使用两个 for 循环。


推荐阅读