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. Group sequence into rows and columns for a TABLE by davidwtbuxton 3 years, 1 month ago
  2. Tags & filters for rendering search results by exogen 6 years ago
  3. Paginator TemplateTag by trbs 6 years ago
  4. Delicious Tag by alcides 5 years, 9 months ago
  5. List divide columns across by Leon 4 years, 11 months ago

Comments

(Forgotten your password?)