Login

table with n items per row using custom modulo tag

Author:
elgreengeeto
Posted:
December 1, 2008
Language:
HTML/template
Version:
Not specified
Score:
0 (after 0 ratings)

As a quick, simple way to take a list of items make a table with n items per row I added a custom template filter for modulo of an integer.

To make the custom filter first create a "templatetags" directory in your application folder then add an empty file called "init.py" in that new directory. Finally add a file "myapp_tags.py" with the above code in it.

In the template you load your custom filter with {% load pictures_tags %} and then you can make a table with n elements per row using a simple for loop and in if statement.

This works because if ( for_loop.counter modulo n ) is zero ("if not" evaluates to True on zero values), then it makes a new table row. You might note that if the number of items in list is a multiple of n, there will be an empty row at the end... preventing that adds needless complexity so I left that out!

 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. Bootstrap Accordian by Netplay4 5 years, 2 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 3 months ago
  5. Pagination Django with Boostrap by guilegarcia 8 years, 5 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.

#

Please login first before commenting.