django template to populate bootstrap rows and columns

后端 未结 5 578
温柔的废话
温柔的废话 2020-12-05 01:14

So here\'s my problem: I\'ve got a bunch of instances of a class. I would like to have a sort of table of these instance objects, so that there is a maximum of six in every

相关标签:
5条回答
  • 2020-12-05 01:44

    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 讨论(0)
  • 2020-12-05 01:49

    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 %}
    
    0 讨论(0)
  • 2020-12-05 01:57

    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 :-)

    0 讨论(0)
  • 2020-12-05 02:03

    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 %}
    
    ...
    
    0 讨论(0)
  • 2020-12-05 02:09

    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 %}
    
    0 讨论(0)
提交回复
热议问题