[Fixed]-Django template to populate bootstrap rows and columns

70πŸ‘

Have no time to explain, but I’ve had similar problem and until i closed this browser page here is a solution

{% for sub_article in articles %}
    {% if forloop.first %}<div class="row">{% endif %}
    <div class="col-xs-4">
            <a href="#">
                {{ sub_article.name }}
            </a>
        </div>
    {% if forloop.counter|divisibleby:3 %}</div><div class="row">{% endif %}
    {% if forloop.last %}</div>{% endif %}
{% endfor %}
πŸ‘€Mark

3πŸ‘

Since forloop.counter starts the index with 1, divisibleby 3 does not work.
So use forloop.counter0 instead.

<div class="row">
{% for product in all_products %}
    {% if forloop.counter0|divisibleby:3 %}
        </div><br><div class="row">
    {% endif %}
        <div class="col-4"></div>
{% endfor %}
πŸ‘€Sharpless512

3πŸ‘

I would recommend to add a custom tag as_chunk. I think it makes the code prettier and more readable.

# app/templatetags/my_tags.py

from math import ceil
from django import template

register = template.Library()

@register.filter
def as_chunks(lst, chunk_size):
    limit = ceil(len(lst) / chunk_size)
    for idx in range(limit):
        yield lst[chunk_size * idx : chunk_size * (idx + 1)]


# app/templates/your-template.html

{% load my_tags %}

...

{% for chunk in elements|as_chunk:6 %}
  <div class="row">
    {% for element in chunk %}
      <div class="col-2">
        {{ element.name }}
      </div>
    {% endfor %}
  </div>
{% endfor %}

...
πŸ‘€Fomalhaut

2πŸ‘

maybe too late but there is simple solution as follow

<div class="container">
    <div class="row">
        {% for product in products %}
            {% if forloop.counter0|divisibleby:3 and not forloop.first %}<div class="w-100"></div>{% endif %}
            <div class="col">{{product.title}}</div>
        {% endfor %}
    </div>
</div>

0πŸ‘

You could make the code a bit more generic. Here’s the logic:

queryset = Class.objects.all()
set_length = queryset.count()

<div class="row">
{% for i in queryset %}
    <div class="span2">
        <p>i.attr</p>
        <p>i.attr</p>
    </div>
    {% if forloop.counter|divisibleby:"6" or forloop.last %}
        </div> <!--end row-->
    {% endif %}
{% endfor %}

I hope this solves your problem πŸ™‚

πŸ‘€Arpit

Leave a comment