djangofor-loopbootstrap-4counter

Django Bootstrap card-deck if forloop divisibleby


I'm trying to use bootstrap cards. But I have problem. When I adding new post to be display as a card, and i display more then 5 they starting to squize. I'm was try to use forloop counter to start new line every time when it display more then 5 cards. But Im doing something wrong. I read everything and everywhere is the same thing. But I'm for sure doing this wrong.

     <div class="card-deck">
    {% for post in post_list %}
    {% if forloop.counter0|divisibleby:3 %}
      <div class="card border-primary mb-3" style="max-width: 20rem;">
          <a href="{% url 'post_detail' post.slug  %}">
              <img style="height: 200px; width: 100%; display: block;" src="{{ post.thumb.url }}" alt="Card image"></a>
                  <div class="card-header">Header</div>
                      <div class="card-body">
                      <h4 class="card-title">{{ post.title }}</h4>
                      <p class="card-text">{{post.content|slice:":200" }}</p>
                      </div>
      </div>   {% endif %}    
  </div>      
 </div>  {% endfor %}          

Reference image


Solution

  • Now you're only seeing every third card (because of the "divisibleby:3"). I'm not exactly sure what you want to achieve, but if you want to show all cards, there are several options. Two of them are card groups (https://getbootstrap.com/docs/4.0/components/card/#card-groups) and card decks (https://getbootstrap.com/docs/4.0/components/card/#card-decks), but they indeed get messy when the number of cards is getting larger. A solution I have used with success is using Bootstrap's grid. The cards will automatically wrap to the next row when the viewport is smaller or the number of cards larger. The code below should work (haven't tested it):

    div class="container-fluid">
        <div class="row">
            {% for post in post_list %}
                <div class="col-auto">
                    <div class="card border-primary mb-3">
                        <a href="{% url 'post_detail' post.slug  %}">
                            <img style="height: 200px; width: 100%; display: block;" src="{{ post.thumb.url }}" alt="Card image">
                        </a>
                        <div class="card-header">
                            Header
                        </div>
                        <div class="card-body">
                            <h4 class="card-title">{{ post.title }}</h4>
                            <p class="card-text">{{ post.content|slice:":200" }}</p>
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>
    </div>