Template filter that divides a list into exact columns

 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. Page numbers with ... like in Digg by Ciantic 4 years, 1 month ago
  2. Pattern to integer list function by marinho 5 years, 5 months ago
  3. Integer list to pattern function by marinho 5 years, 5 months ago
  4. Improved many-page pagination by dokterbob 2 years, 8 months ago
  5. Git recent commits template tag by david 4 years, 9 months ago

Comments

(Forgotten your password?)