views:

69

answers:

1

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!

+3  A: 

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>
Daniel Roseman