Login

Template filter that divides a list into exact columns

Author:
davmuz
Posted:
January 20, 2012
Language:
Python
Version:
1.3
Tags:
filter template-filter list columns
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. Group sequence into rows and columns for a TABLE by davidwtbuxton 4 years, 4 months ago
  2. Tags & filters for rendering search results by exogen 7 years, 3 months ago
  3. Paginator TemplateTag by trbs 7 years, 3 months ago
  4. Delicious Tag by alcides 7 years ago
  5. List divide columns across by Leon 6 years, 1 month ago

Comments

Please login first before commenting.