Shane Reustle
Shane Reustle

Reputation: 8952

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><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!

Upvotes: 2

Views: 585

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

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>

Upvotes: 11

Related Questions