使用 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屋!