table with n items per row using custom modulo tag

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# add following to mysite/myapp/templatetags/myapp_tags.py

from django import template
register = template.Library()

@register.filter
def mod(value, arg):
    return value % arg


#put following in your template and change mod:5
#according to the number of cells per table row desired

{% load pictures_tags %}

<table>
<tr>
{% for item in list %}
  <td>
  <!--CELL CONTENT-->
  </td>
  {% if not forloop.counter|mod:5 %}
    </tr><tr>
  {% endif %}
{% endfor %}
</tr>
</table>

Comments

Sam Barnes (on February 11, 2009):

A couple of points:

You can use the built in divisibleby template tag instead of making a custom one. It does the same thing- Im not sure why it isn't called mod or modulo!

If the list length is also divisible by n, you'll get an extra row. A better solution uses a forloop0 to open the row and a forloop to close the row within if statements.

Thanks for the inspiration though- this snippet certainly put me in the right direction.

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.