如何通过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 exactlymy_vartimes. Whenmy_varequals 10, this spits out 10 cards without any hardcoded repetition. Thecard_indexvariable can be used for unique elements (like the image alt text) if needed. - Proper Bootstrap Structure: Moved the loop inside the
card-deckcontainer 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', ...}, ...]), swaprange(my_var)with{% for book in books %}and usebook.booknameto 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_varisn'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
相关产品推荐
相关产品推荐

