[Answer]-Django template slice

1👍

What about using the code, Luke ?

https://github.com/django/django/blob/master/django/template/defaultfilters.py

@register.filter("slice", is_safe=True)
def slice_filter(value, arg):
    """
    Returns a slice of the list.

    Uses the same syntax as Python's list slicing; see
    http://www.diveintopython3.net/native-datatypes.html#slicinglists
    for an introduction.
    """
    try:
        bits = []
        for x in arg.split(':'):
            if len(x) == 0:
                bits.append(None)
            else:
                bits.append(int(x))
        return value[slice(*bits)]

    except (ValueError, TypeError):
        return value # Fail silently.

To make a long story short: the filter doesn’t have access to the context, so it cannot resolve variables, and only work with litteral values.

Leave a comment