使用 Jinja 迭代引导卡

问题描述 投票:0回答:1

我正在尝试使用 Jinja 从 Bootstrap 迭代卡片组内的卡片,因此 1 组内的卡片不超过 4 张,但我最终以 1 张卡片并排完成。这是我的代码:

{% set n = 0 %}
{% for vid in videos %}
    {% if n % 4 == 0 %}
        {% if n % 4 == 0 %}
            </div> <!-- Close previous card-group -->
        {% endif %}
        <div class="card-group"> <!-- Start a new card-group -->
    {% endif %}
    <div class="card">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
    {% set n = n + 1 %}
{% endfor %}
</div>

我尝试改变不同div的位置,但效果并不明显

python html loops flask jinja2
1个回答
0
投票

卡组的问题在于,一个组中必须包含与其他所有卡一样多的卡,因为如果数量较少,组中的卡就会缩放。但是,您的视频列表的数量可能有所不同,并且并不总是包含能被 4 整除的数字。

我建议使用网格卡。在这种情况下,它们的大小都相同,未使用的空间仍然可用。

<div class="row row-cols-1 row-cols-sm-2 row-cols-md-4 g-4">
    {% for vid in vids -%}
    <div class="col">
        <div class="card h-100">
            <img src="..." class="card-img-top" alt="...">
            <div class="card-body">
                <h5 class="card-title">Card title {{ loop.index }}</h5>
                <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
            </div>
            <div class="card-footer">
                <small class="text-body-secondary">Last updated 3 mins ago</small>
            </div>
        </div>
    </div>
    {% endfor -%}
</div>
© www.soinside.com 2019 - 2024. All rights reserved.