Django template template

{% with start=0 end=entries.number|add:"2" %}
    {{ paginator.page_range|slice:"start:end" }}
    {{ start }}, {{ end }}
    {{ paginator.page_range|slice:"0:3" }}
{% endwith %}

      

Why is the Django 1.5 templating engine producing the following output for the above code:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
0, 3
[1, 2, 3]

      

0


source to share


1 answer


How about using 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 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.

      

In short: the filter does not have access to the context, so it cannot resolve variables and only works on literal values.

+1


source







All Articles