Ticket #6285: columns_rows_filters.diff

File columns_rows_filters.diff, 2.1 KB (added by Taylan Pince, 16 years ago)

Suggestion for filters to slice lists into rows and columns

  • django/template/defaultfilters.py

     
    633633unordered_list.is_safe = True
    634634unordered_list.needs_autoescape = True
    635635
     636def columns(thelist, n):
     637    """
     638    Breaks a list into ``n`` number of columns, filling up each column to the
     639    maximum equal length possible. This filter will always return ``n``
     640    columns, even if some are empty.
     641
     642    Usage::
     643
     644        {% for item_column in item_list|columns:3 %}
     645        <li class="column">
     646            <ul>
     647                {% for item in item_column %}
     648                <li><a href="#">{{ item }}</a></li>
     649                {% endfor %}
     650            </ul>
     651        </li>
     652        {% endfor %}
     653
     654    """
     655    try:
     656        n = int(n)
     657        thelist = list(thelist)
     658    except (ValueError, TypeError):
     659        return [thelist]
     660
     661    list_len = len(thelist)
     662    split = list_len // n
     663
     664    if list_len % n != 0:
     665        split += 1
     666
     667    return [thelist[split*i:split*(i+1)] for i in range(n)]
     668
     669def rows(thelist, n):
     670    """
     671    Breaks a list into rows with a maximum number of ``n`` elements in each.
     672
     673    Usage::
     674
     675        {% for item_row in item_list|rows:4 %}
     676        <li class="row">
     677            <ul>
     678                {% for item in item_row %}
     679                <li><a href="#">{{ item }}</a></li>
     680                {% endfor %}
     681            </ul>
     682        </li>
     683        {% endfor %}
     684
     685    """
     686    try:
     687        n = int(n)
     688        thelist = list(thelist)
     689    except (ValueError, TypeError):
     690        return [thelist]
     691
     692    newlists = [list() for i in range(int(ceil(len(thelist) / float(n))))]
     693
     694    for i, val in enumerate(thelist):
     695        newlists[i/n].append(val)
     696
     697    return newlists
     698
    636699###################
    637700# INTEGERS        #
    638701###################
     
    896959register.filter(truncatewords)
    897960register.filter(truncatewords_html)
    898961register.filter(unordered_list)
     962register.filter(columns)
     963register.filter(rows)
    899964register.filter(upper)
    900965register.filter(urlencode)
    901966register.filter(urlize)
Back to Top