Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of characters with Django Template filter

People also ask

What does {{ this }} mean in Django?

What does {{ name }} this mean in Django Templates? Django. It will be displayed as name in HTML. The name will be replaced with values of Python variable. {{ name }} will be the output.

What does filter do in Django template?

Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.

What is safe filter in Django template?

The safe filter indicates that the value is known to be safe and therefore does not need to be escaped. For example, given the following: blurb = '<p>You are <em>pretty</em> smart!</ p>' This would return unescaped HTML to the client: {{ blurb|safe }}

What does {% include %} do in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.


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


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.