Limit number of characters with Django Template filter

PythonDjangoDjango Templates

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

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" }}

Solution 2 - Python

There is an official built-in filter:

{{ variable|truncatechars:255 }}

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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.

Solution 6 - Python

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShane ReustleView Question on Stackoverflow
Solution 1 - PythonheckjView Answer on Stackoverflow
Solution 2 - PythonnorthbenView Answer on Stackoverflow
Solution 3 - PythonPaul FennemaView Answer on Stackoverflow
Solution 4 - PythonFelipe FrançaView Answer on Stackoverflow
Solution 5 - PythonTomek KopczukView Answer on Stackoverflow
Solution 6 - PythonVincentView Answer on Stackoverflow