You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Jinja2循环在满足条件时生成多张Bootstrap 4卡片?

Got it, let's get this working so you can dynamically generate the exact number of Bootstrap 4 cards based on your my_var value. Here's the corrected code with clear explanations:

Complete Working Code

{% set my_var = 10 %}
<div class="row justify-content-center mt-4">
  <div class="col-12 col-md-10 col-lg-8">
    <div class="card-deck">
      {% if my_var == 10 %}
        <!-- Loop exactly my_var times using Jinja2's range() -->
        {% for card_index in range(my_var) %}
          <div class="card">
            <img src="{{ url_for('static', filename='dist/img/rename.svg') }}" 
                 class="card-img-top" 
                 alt="Card {{ card_index + 1 }}" 
                 width="150" 
                 height="200">
            <div class="card-body">
              <!-- Note: Replace static x[0] references if you have dynamic data -->
              <h5 class="card-title">{{ x[0]['bookname'] }}</h5>
              <p id="text-card">Description: {{ v }}</p>
              <p class="card-text"><small>Donated by: {{ x[0]['donatedby'] }}</small></p>
              <a href="" class="btn btn-outline-success btn-pill">
                <i class="far fa-paper-plane"></i> Request
              </a>
            </div>
          </div>
        {% endfor %}
      {% else %}
        <!-- Insert your "other operation" logic here -->
        {{ v }}
      {% endif %}
    </div>
  </div>
</div>

Key Changes & Explanations

  • Automatic Loop Generation: Used {% for card_index in range(my_var) %} to loop exactly my_var times. When my_var equals 10, this spits out 10 cards without any hardcoded repetition. The card_index variable can be used for unique elements (like the image alt text) if needed.
  • Proper Bootstrap Structure: Moved the loop inside the card-deck container so Bootstrap's responsive card layout works as intended—cards will space evenly and wrap correctly on smaller screens.
  • Dynamic Data Tip: Right now you're using x[0]['bookname'] which shows the same content on every card. If you have a list of books (e.g., books = [{'bookname': 'Book 1', ...}, ...]), swap range(my_var) with {% for book in books %} and use book.bookname to display unique content per card.
  • Clean Else Branch: Kept your original else logic but ensured it's placed outside the loop so it only runs when my_var isn't 10.

Bonus: Fix Responsive Card Wrapping

Bootstrap 4's card-deck can behave oddly on mobile. Add this CSS to your stylesheet to make cards stack vertically on small screens:

@media (max-width: 767px) {
  .card-deck {
    flex-direction: column;
  }
  .card-deck .card {
    margin-bottom: 1rem;
  }
}

内容的提问来源于stack exchange,提问作者vatsalay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:05:39