list_to_columns.py 1.06 KB
Newer Older
1
# Based on https://www.djangosnippets.org/snippets/889/
2

3
from django import template
4

5 6 7
register = template.Library()

class SplitListNode(template.Node):
8
    def __init__(self, list, cols, new_list):
9
        self.list = list
10
        self.cols = cols
11 12
        self.new_list = new_list

13
    def split_seq(self, list, cols=2):
14
        start = 0
15
        for i in range(cols):
16 17
            stop = start + len(list[i::cols])
            yield list[start:stop]
18
            start = stop
19 20

    def render(self, context):
21
        context[self.new_list] = self.split_seq(context[self.list], int(self.cols))
22 23
        return ''

24 25
def list_to_columns(parser, token):
    """Parse template tag: {% list_to_columns list as new_list 2 %}"""
26
    bits = token.contents.split()
27
    if len(bits) != 5:
28
        raise template.TemplateSyntaxError("list_to_columns list as new_list 2")
29
    if bits[2] != 'as':
30
        raise template.TemplateSyntaxError("second argument to the list_to_columns tag must be 'as'")
31 32
    return SplitListNode(bits[1], bits[4], bits[3])
list_to_columns = register.tag(list_to_columns)