django template to populate bootstrap rows and columns

后端 未结 5 577
温柔的废话
温柔的废话 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 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 %}
      
    {% for element in chunk %}
    {{ element.name }}
    {% endfor %}
    {% endfor %} ...

提交回复
热议问题