html - 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 个对象,然后跳到下一行,依此类推...
解决方案
您可以使用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 循环。
推荐阅读
- performance - k8s 任务减慢,没有过多的 CPU 或 RAM 使用
- substrate - 在windows vscode上编译substrate-node-template时出错
- flutter - 颤振:如何创建这样的底部导航栏
- paypal - Paypal javascript sdk onClick 不会阻止弹出窗口显示
- c - 如何从C中的浮点类型中删除点?
- php - php如何做一个循环来计算测验网站的分数
- java - 是否可以在不限制大小的情况下创建无限流?
- ubuntu - 使用“apt”时,如何避免出现 postfix 错误 75?
- arrays - 比较两个文本文件,相同的点,不同的点描述
- c++ - 将 std::wstring 转换为 WCHAR 数组