Limit number of characters with Django Template filter

人走茶凉 提交于 2019-12-02 20:00:59
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.

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

Usage would be something like

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

There is an official built-in filter:

{{ variable|truncatechars:255 }}

If do you want to truncate by word, take a look at this https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#truncatechars

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.

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.

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.

You can achieve a responsive truncated text using this:

.class {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!