django template rows of multiple items

前端 未结 4 717
梦毁少年i
梦毁少年i 2020-12-13 15:26

I\'m creating a catalogue, where there is a list of items of undefined length. I want to spit it out in rows with three columns each. So I have the following html:



        
相关标签:
4条回答
  • 2020-12-13 16:07

    You can use forloop.counter variable and divisibleby filter. The code will be close to this:

    {% for item in items %}
        {% if forloop.first %}
            <div class="row">
        {% endif %}
        <div class="three columns">{{ item }}</div>
        {% if forloop.counter|divisibleby:"3" %}
            </div>
            {% if not forloop.last %}
                <div class="row">
            {% endif %}
        {% endif %}
        {% if forloop.last %}
             </div>
        {% endif %}
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-13 16:10

    Sorry don't have enough reputation to just comment jpic's answer(the accepted one), for Jinja2, use:

    <div class="row">
    {% for item in items %}
        <div class="three columns">{{ item }}
        </div>
        {% if loop.index is divisibleby(3) %}
    </div>
    <div class="row">
        {% endif %}
    {% endfor %}
    </div>
    

    details are here.

    0 讨论(0)
  • 2020-12-13 16:12

    You could try to create a custom template filter, that would return a list of list of 3-items.

    Quick attempt :

    @register.filter
    def splitByThree(data):
        return [l[i:i+3] for i in range(0, len(l), 3)]
    

    And then in your template :

    {% load splitByThree %}
    
    {% for list in data|splitByThree %}
    <div class="row">
    {% for item in list %}
    <div class="three columns">{{ item }}</div>
    {% endfor %}
    </div>
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-13 16:24

    Try something like this:

    <div class="row">
    {% for item in items %}
        <div class="three columns">{{ item }}
        </div>
        {% if forloop.counter|divisibleby:3 %}
    </div>
    <div class="row">
        {% endif %}
    {% endfor %}
    </div>
    
    0 讨论(0)
提交回复
热议问题