Limit number of characters with Django Template filter

Solution 1:

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:

There is an official built-in filter:

{{ variable|truncatechars:255 }}

Solution 3:

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:

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