Python 使用 Django 模板过滤器限制字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3484149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:18:41  来源:igfitidea点击:

Limit number of characters with Django Template filter

pythondjangodjango-templates

提问by Shane Reustle

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.

我正在尝试在项目列表中输出描述的前 255 个字符,并且正在寻找一种方法来获取它。

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

示例:我有一个包含 300 个左右字符的变量。

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

我这样称呼那个变量, {{ my_variable|characterlimit:255 }}

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

它只会返回该变量的前 255 个字符。

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!

如果这个标签不存在,我将简单地创建它(并建议它进入 django),但我想在我花时间这样做之前确保它不存在。谢谢!

采纳答案by heckj

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.

如果“my_variable”是字符串,您可以利用切片过滤器,它将字符串视为字符列表。如果是一组单词,粗略的等价词是截词- 但这听起来不太像您的需要。

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

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

Usage would be something like

用法类似于

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

回答by Tomek Kopczuk

It doesn't exist unfortunately. There are moves to implement it, but it's still in the design stage (well, implemented, but waiting for design decision), as described here.

不幸的是它不存在。有移动来实现它,但它仍然是在设计阶段(当然,实现的,而是在等待设计决定),如所描述这里

Patch attached to that ticket contains implementation.

附加到该票证的补丁包含实现。

回答by Felipe Fran?a

回答by Paul Fennema

A more simple way by using the standard template tag is:

使用标准模板标签的更简单方法是:

{{ variable|stringformat:".10s" }}

In this case the 10 is the position argument and for a string it is the maximum number of characters to be displayed.

在这种情况下,10 是位置参数,对于字符串,它是要显示的最大字符数。

回答by northben

There is an official built-in filter:

有一个官方内置过滤器

{{ variable|truncatechars:255 }}

回答by Vincent

Using a templatefilter for truncating your text isn't really suitable for a responsive design. Therefore you could also use css to truncate your text that is responsive. I know the OP asked to do this with a django templatefilter.

使用模板过滤器截断文本并不适合响应式设计。因此,您还可以使用 css 截断响应式文本。我知道 OP 要求使用 django 模板过滤器执行此操作。

You can achieve a responsive truncated text using this:

您可以使用以下方法实现响应式截断文本:

.class {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}