Top Commentators

  • Two guys and a Beer - Episode 85
  • Jam Session 2
  • Two guys and a Beer - Episode 84

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 :)

Share:
  • Digg
  • del.icio.us
  • Facebook
  • Posterous
  • Reddit
  • Twitter
  • HackerNews
  • FriendFeed
  • Hyves
  • RSS

Related:

  1. [Django] Dynamic redirection after login
  2. Django: Reverse HTTP redirect with parameters

4 comments to Django template filter: Show list of objects as table with fixed number of columns

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>