Jinja2: Create new row for every 3 items

后端 未结 2 1693
天命终不由人
天命终不由人 2021-01-31 04:09

Currently for every article in articles a new div with class span4 is created. Instead for each row I would like to limit it\'s content to three span\'s and create a new row on

相关标签:
2条回答
  • 2021-01-31 04:44

    You can use loop.index0 and loop.last inside the for loop. Here is the for-loop documentation.

    Example:

    {% extends "base.html" %}
    {% block content %}
    <div class="container-fluid">
      <legend></legend>
      <div class="row-fluid" id="main">
          {% for article in articles %}
          {% if loop.index0 % 3 == 0 %}
          <div class="row">
          {% endif %}
              <div class="span4">
                  ...
              </div>
          {% if loop.index0 % 3 == 2 or loop.last %}
          </div>
          {% endif %}
          {% endfor %}
      </div>
    </div>
    {% endblock %}
    

    The loop.last clause should close the last row even if there were less than 3 items. <div> should start when loop.index0 gives 0 as the remainder and should end when 2 is the remainder

    Another alternative would be to group the items into rows before passing them into the template, then you can just issue two for-loops one inside the other.

    0 讨论(0)
  • 2021-01-31 04:59

    The best way to do this is to use the built in batch filter to break up your list into groups of three:

    {% for article_row in articles | batch(3, '&nbsp;') %}
    <div class="row">
        {% for article in article_row %}
        <div class="span4">{{ article }}</div>
        {% endfor %}
    </div>
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题