Login

sublist

Author:
nofactor
Posted:
November 20, 2007
Language:
Python
Version:
.96
Score:
-5 (after 5 ratings)

Usage: list|sublist:"a:b"

Returns list[a:b]

Accepts ":b" and "a:" shortcuts

Note that the double quotes are necessary

 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
31
32
33
34
from django import template
register = template.Library()

@register.filter
def sublist(value, arg):
    """
    Usage: list|sublist:"a:b"
    Returns list[a:b]
    Accepts ":b" and "a:" shortcuts
    Note that the double quotes are necessary
    """
    try:
        arg = str(arg)
        mylist = list(value)
    except (ValueError, TypeError):
        return value
    if arg.find(':') < 0:
        return value
    a, b = arg.split(':')[:2]
    if a == "":
        a = None
    else:
        try:
            a = int(a)
        except ValueError:
            return value
    if b == "":
        b = None
    else:
        try:
            b = int(b)
        except ValueError:
            return value
    return mylist[a:b]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

nofactor (on November 21, 2007):

ok, i'm reinventing the wheel! is it possible to remobe a snippet?

#

nofactor (on November 21, 2007):

To admins: Please remove this snippet

#

Please login first before commenting.