Django template filter: Show list of objects as table with fixed number of columns
I recently ran into the following problem: I needed to be able to display a list of users in a table that had a maximum of X columns. Since I could not find the solution on the Internet I decided to give it a try and here is my resulting template filter to do it:
def tablecols(data, cols): rows = [] row = [] index = 0 for user in data: row.append(user) index = index + 1 if index % cols == 0: rows.append(row) row = [] # Still stuff missing? if len(row) > 0: rows.append(row) return rows register.filter_function(tablecols)
Then you can use it in your templates like so:
<table> {% for row in members|tablecols:5 %} <tr> {% for member in row %} <td> {% show_simple_profile member user %} </td> {% endfor %} </tr> {% endfor %} </table>
It will break down the “members” list into a list of lists, each of the first being a group of (in this case) 5 users max.
Have fun

Comments
Post a Comment