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
- If in list template tag by udfalkso 4 years, 10 months ago
- Filter on Multiple M2M Objects Simultaneously by axiak 5 years, 1 month ago
- Add ValidationError to a field instead of __all__ during Form.clean() by guettli 3 years, 7 months ago
- highlight pattern by nicolaslara 3 years ago
- SerializedObjectField by dominno 2 years, 2 months 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
#