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>

More like this

  1. Group sequence into rows and columns for a TABLE by davidwtbuxton 2 years, 3 months ago
  2. Filter to add zero-width space to break up long words by jayliew 8 months ago
  3. Reshape list for table, flatten index in nested loops by aquagnu 5 years, 3 months ago
  4. If modulo template tag by voidberg 5 years, 9 months ago
  5. Bulk Insert - updated 5/9/2008 by coolie 5 years, 7 months ago

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