Django模板切片 [英] Django template slice
本文介绍了Django模板切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{% 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模板引擎为上述代码生成以下输出:
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]
推荐答案
如何使用代码,Luke?
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.
这篇关于Django模板切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文