【问题标题】:Django template sliceDjango 模板切片
【发布时间】:2013-04-30 14:17:43
【问题描述】:
{% with start=0 end=entries.number|add:"2" %}
    {{ paginator.page_range|slice:"start:end" }}
    {{ start }}, {{ end }}
    {{ paginator.page_range|slice:"0:3" }}
{% endwith %}

为什么 Django 1.5 模板引擎会为上述代码生成以下输出:

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

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    卢克,使用代码怎么样?

    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.
    

    长话短说:过滤器无法访问上下文,因此它无法解析变量,只能处理文字值。

    【讨论】:

      猜你喜欢
      • 2017-04-24
      • 2013-05-08
      • 2012-02-08
      • 2014-06-18
      • 2010-12-26
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      相关资源
      最近更新 更多