112👍
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.
truncatewords
also adds an ellipsis ...
at the end of the truncated result.
Usage would be something like
{{ my_variable|slice:":255" }}
- [Django]-Why am I getting this error in Django?
- [Django]-Writing a __init__ function to be used in django model
- [Django]-Django ModelForm to have a hidden input
8👍
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.
- [Django]-Django Reverse with arguments '()' and keyword arguments '{}' not found
- [Django]-What is reverse()?
- [Django]-Where's my JSON data in my incoming Django request?
7👍
If do you want to truncate by word, take a look at this
https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#truncatechars
- [Django]-Django get list of models in application
- [Django]-Django template includes slow?
- [Django]-How to expire session due to inactivity in Django?
0👍
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.
- [Django]-Iterate over model instance field names and values in template
- [Django]-How to annotate Count with a condition in a Django queryset
- [Django]-Django – Annotate multiple fields from a Subquery
0👍
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;
}
- [Django]-Multiple Models in a single django ModelForm?
- [Django]-How to produce a 303 Http Response in Django?
- [Django]-Is this the right way to do dependency injection in Django?