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>
精彩评论