Задать вопрос

Тел: +7 965 3737 888





table with n items per row using custom modulo tag

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!

Вопрос полезен? Да0/Нет0

Ответы (1):

Ответ полезен? Да0/Нет0

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.