Django template tag for truncating text

Django has a word tag truncatewords template tag that trims text for a given number of words. But there is nothing like truncatechars.

What is the best way to cut out text in a template with a given character length limit?

+65
django django-templates
Mar 08 2018-11-11T00:
source share
8 answers

It was recently added in Django 1.4. eg:.

 {{ value|truncatechars:9 }} 

See document here

+127
Apr 24 2018-12-12T00:
source share
 {{ value|slice:"5" }}{% if value|length > 5 %}...{% endif %} 

Update

Starting with version 1.4, Django has a built-in template tag for this:

 {{ value|truncatechars:9 }} 
+51
Mar 18 '11 at 17:11
source share

I created my own template filter, which adds a "..." to the end (last word) of the line (truncated):

 from django import template register = template.Library() @register.filter("truncate_chars") def truncate_chars(value, max_length): if len(value) > max_length: truncd_val = value[:max_length] if not len(value) == max_length+1 and value[max_length+1] != " ": truncd_val = truncd_val[:truncd_val.rfind(" ")] return truncd_val + "..." return value 
+9
Aug 11 2018-11-11T00:
source share

Here it is in the Django documentation, Built-in Tags and Template Filters: truncatechars

+3
Jan 09 '12 at 18:53
source share

You must write your own template filter: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

See how truncatewords is embedded in django.utils.text

+2
Mar 08 2018-11-21T00:
source share
+1
Mar 08 2018-11-11T00:
source share

Adding the "truncate" filter was a function request for 4 years, but finally landed in the trunk, as I understand it https://code.djangoproject.com/ticket/5025 - so we are waiting for the next release or use the baggage.

0
Aug 11 2018-11-11T00:
source share



All Articles