使用Django模板过滤器限制字符数 [英] Limit number of characters with Django Template filter
问题描述
我正在尝试在商品列表中输出描述的前255个字符,并正在寻找一种方法来获取它。
I am trying to output the first 255 characters of a description on a list of items and am looking for a method to get that.
示例:我有一个包含300个左右字符的变量。
Example: I have a variable that contains 300 or so characters.
我这样称呼该变量, {{my_variable | characterlimit:255}}
,它将仅返回该变量的前255个字符。
and it would return only the first 255 characters of that variable.
如果此标记没有,如果不存在,我将简单地创建它(并建议将它放入django),但是我想确保在花时间之前没有创建它。谢谢!
If this tag doesn't exist, I will simply create it (and suggest that it goes into django), but I wanted to make sure it didn't before I took the time to do that. Thanks!
推荐答案
如果 my_variable是字符串,则可以利用切片过滤器,该过滤器将字符串视为字符列表。如果是一组单词,则大致等同于 truncatewords -但这听起来不太像您的需要。
If the "my_variable" is a string, you can take advantage of the slice filter, which treats the string as a list of characters. If it's a set of words, the rough equivilant is truncatewords - but that doesn't quite sound like your need.
truncatewords
还添加了省略号 ...
截断结果的结尾。
truncatewords
also adds an ellipsis ...
at the end of the truncated result.
用法类似于
{{ my_variable|slice:":255" }}
这篇关于使用Django模板过滤器限制字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!