广告位

django模板用slice过滤器限制字数

您现在的位置是:主页 > 编程 >

2021年9月25日 11:31编程 > 2709人已围观

简介 如果" my_variable"是字符串,则可以利用切片过滤器,该过滤器将字符串视为字符列表。如果是一组单词,则大致等同于 truncatewords -但这听起来不太像您的需要。 truncatewords 还添加了省略号 ... 截断结果的结尾。...

如果" my_variable"是字符串,则可以利用切片过滤器,该过滤器将字符串视为字符列表。如果是一组单词,则大致等同于 truncatewords -但这听起来不太像您的需要。


truncatewords 还添加了省略号 ... 截断结果的结尾。


用法类似于



  {{my_variable | slice:":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.

Example: I have a variable that contains 300 or so characters.

I call that variable like this, {{ my_variable|characterlimit:255 }}

and it would return only the first 255 characters of that variable.

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!

解决方案

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.

truncatewordsalso adds an ellipsis ... at the end of the truncated result.

Usage would be something like

{{ my_variable|slice:":255" }}


Tags: django  模板 

广告位
    广告位
    广告位

站点信息

  • 文章统计113篇文章
  • 标签管理标签云
  • 微信公众号:扫描二维码,关注我们