Login

Template filter that divides a list into exact columns

Author:
davmuz
Posted:
January 20, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Template filter that divides a list into an exact number of columns. The number of columns is guaranteed.

Example (list == [1,2,3,4,5,6,7,8,9,10]):

{% for column in list|columns:3 %}
<ul>
    {% for item in column %}
    <li>{{ item }}</li>
    {% endfor %}
</ul>
{% endfor %}

Result:

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
<ul>
    <li>5</li>
    <li>6</li>
    <li>7</li>
</ul>
<ul>
    <li>8</li>
    <li>9</li>
    <li>10</li>
</ul>

By Davide Muzzarelli

 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
28
29
30
from django.template import Library
from itertools import cycle

register = Library()

@register.filter
def exact_columns(items, number_of_columns):
    """Divides a list in an exact number of columns.
    The number of columns is guaranteed.
    
    Examples:
    
        8x3:
        [[1, 2, 3], [4, 5, 6], [7, 8]]
        
        2x3:
        [[1], [2], []]
    """
    try:
        number_of_columns = int(number_of_columns)
        items = list(items)
    except (ValueError, TypeError):
        return [items]
    
    columns = [[] for x in range(number_of_columns)]
    actual_column = cycle(range(number_of_columns))
    for item in items:
        columns[actual_column.next()].append(item)
    
    return columns

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.