django: templates how to fill a table of 3 items in a row

后端 未结 2 773
猫巷女王i
猫巷女王i 2021-01-01 05:06

I want to fill a table with a list of results. But not sure how to tell the template that it\'s time to close current and start a new one, after 3 products was already disp

相关标签:
2条回答
  • 2021-01-01 05:37

    Easiest way is to use the divisibleby filter.

    {% for item in results %}
    {% if forloop.counter0|divisibleby:3 %}<tr>{% endif %}
    <td>{{ item }}</td>
    {% if forloop.counter|divisibleby:3 %}</tr>{% endif %}
    {% endfor %}
    
    0 讨论(0)
  • 2021-01-01 05:54

    Even better is to add a foorloop.last condition to add </tr> at the end of the last row:

    {% for item in results %}
    {% if forloop.counter0|divisibleby:3 %}<tr>{% endif %}
    <td>{{ item }}</td>
    {% if forloop.counter|divisibleby:3 or forloop.last %}</tr>{% endif %}
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题