In my application, I often need to convert a list of objects and
arrange them into a table with a specified number of columns. Now I'm
sure you can achieve the formatting of the table by using the loop
counters and such to test when to output the <TR> tags and such, but
I've found the following filter efficient and preferrable and I'd like
to recommend adding it to the django core templates since it's a very
common problem:
Basically, you just add the filter inside a {% for %} tag. eg:
<TABLE>
{% for row in articles.get_list|tabularize: 3 %}
<TR>
{% for article in row %}
<TD>
{% if article %}
{{ article }}
{% endif %}
</TD>
{% endfor %}
</TR>
{% endfor %}
</TABLE>
Not that this filter adds None references to fill in the remaining
columns on the last row.
Here's the code for the filter:
def tabularize(value, cols):
"""modifies a list to become a list of lists
eg [1,2,3,4] becomes [[1,2], [3,4]] with an argument of 2"""
try:
cols = int(cols)
except ValueError:
return [value]
return map(*([None] + [value[i::cols] for i in range(0,
cols)]))
template.register_filter('tabularize', tabularize, True)