truncatewords
Django的模板过滤器truncatewords,取这个模板变量的前 N 个单词,不可用于中文。
将字符串截短为指定的单词个数。如果指定的单词数量小于字符串中包含的单词个数,则会在字符串末尾添加一个省略号(…)。
输入
{{ "Ground control to Major Tom." | truncatewords: 3 }}
输出
Ground control to...
(1)自定义省略号
truncatewords
还支持第二个可选参数,用于指定一个字符序列,此字符序列将被添加到截短字符串的后面。默认是省略号(…),但是你可以按照你的需要传递一个新的。
输入
{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}
输出
Ground control to--
(2)无省略号
如果你不希望在末尾添加省略号,可以将 truncatewords
的第二个参数设置为空字符串:
输入
{{ "Ground control to Major Tom." | truncatewords: 3, "" }}
输出
Ground control to
truncatechars
Django的模板过滤器truncatechars,取这个模板变量的前 N 个字符,可用于中文。
如果字符串包含的字符总个数多于指定的字符数量,那么会被截断掉后面的部分。截断的字符串将以 ... 结尾。
输入
{{ "Ground control to Major Tom." | truncatechars: 5 }}
输出
Grou…
注意:
...也占了一个字符。
truncatechars截取的文本后面没有省略号的问题:
是一个bug,编码为
en-us
时是正常的;编码为zh-hans
就有问题在Django的setting文件中:
LANGUAGE_CODE = 'zh-hans' #使用truncatechars不添加省略号(...) LANGUAGE_CODE = 'en-us' #使用truncatechars会正常添加省略号(...)
slice
Django的模板过滤器slice, 取变量前 N 个字符,可用于中文。
只传入一个参数时将返回此参数作为下标所对应的单个字符。第二个参数是可选的,用于指定返回的子字符串的长度。
String indices are numbered starting from 0.
输入
{{ "Liquid" | slice: 0 }}
输出
L
输入
{{ "Liquid" | slice: 2 }}
输出
q
输入
{{ "Liquid" | slice: 2, 5 }}
输出
quid
If the first parameter is a negative number, the indices are counted from the end of the string:
输入
{{ "Liquid" | slice: -3, 2 }}
输出
ui
总结:
假设content为大于3个单词且第一个单词大于3个字符的字符串变量。
{{ content | truncatewords: 3 }} 取变量前3个单词,以...结尾,不可用于中文
{{ content | truncatewords: 3 }} 取变量前2个字符,以...结尾,可用于中文
{{ content | slice: 3 }} 取变量前3个字符,可用于中文