开发者

How to properly columnize tables in a Django template

I am currently trying to break a list of people (aprox 20 to 30 items) into a table with 4 columns. Here is my current code.

<table>
{% for person in people %}
    {% cycle "<tr>&l开发者_如何学Pythont;td>" "<td>" "<td>" "<td>" %}
        {{ person }}
    {% cycle "</td>" "</td>" "</td>" "</td></tr>" %}
{% endfor %}
</table>

Obviously, this is pretty ugly, and doesn't always close the last TR tag. One alternative I found was to break my list of people into multiple lists of 4 people, and then loop through each of those lists. I was hoping there was an easier way to do this in the templates side alone, without extending django templates myself (which I also found and considered)

Thanks!


Use the divisibleby filter.

<tr>
{% for person in people %}
    <td>{{ person }}</td>
    {% if forloop.counter|divisibleby:4 and not forloop.last %}</tr><tr>{% endif %}
{% endfor %}
</tr>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜