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
- Wrapper-function Pattern by Archatas 3 years, 1 month ago
- Past days template filter by ramen 3 years, 6 months ago
- Template tag: split list to n sublists by movielady 4 years, 10 months ago
- Accept Header Middleware by kioopi 5 years, 1 month ago
- Yet another list partitioning filter by AndrewIngram 4 years ago
Comments
How is this different from Django's existing slice tag?
#
ok, i'm reinventing the wheel! is it possible to remobe a snippet?
#
To admins: Please remove this snippet
#