Django里有 truncatewords
和 slice
两个模板过滤器可用于字符截取。truncatewords
不支持中文,所以一般情况下,中文字符截取用 slice
即可。但两者还是有区别的,比如有开发者提及后面的点点点。那么,就有了下面的解决方案,放这里备份。
(以下代码来源点这里,2009年的资源)
#coding=utf8
from django.template import Library
from django.template.defaultfilters import stringfilter
register = Library()
@stringfilter
def truncatehanzi(value, arg):
"""
Truncates a string after a certain number of words including
alphanumeric and CJK characters.
Argument: Number of words to truncate after.
"""
try:
bits = []
for x in arg.split(u':'):
if len(x) == 0:
bits.append(None)
else:
bits.append(int(x))
if int(x) < len(value):
return value[slice(*bits)] + '...'
return value[slice(*bits)]
except (ValueError, TypeError):
return value # Fail silently.
register.filter('truncatehanzi', truncatehanzi)