Django template slice

北战南征 提交于 2019-12-12 03:02:45

问题


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

Why Django 1.5 template engine produces the following output for the above code:

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

回答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.



来源:https://stackoverflow.com/questions/16405305/django-template-slice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!