Simple Character Truncate Filter And Dot Dot Dot Variant
A basic filter tag for truncating long strings and optionally appending a "…". I used this to clean up long URLS at Arkayne. See list on right side of main page.
Background
Say you have:
- http://www.someverylongurl.com/with/lots/of/characters/that/dont/fit/in/a/line
You want to display only 40 chars:
- http://www.someverylongurl.com/lots/o…
Code
The implementation for the plain and dot dot dot filter is wrapped into one file. Both are pretty strainght forward.
from django import template
register = template.Library()
@register.filter("truncate")
def truncate(value, size):
return value[0:size]
@register.filter("truncate_dot")
def truncate_dot(value, size):
if len(value) > size and size > 3:
return value[0:(size-3)] + '...'
else:
return value[0:size]
Integration
Include the newly created filter and use it on any string. Note that the example shows both the dot dot dot variant and the plain truncate.
{% load truncate_filter %}
Most Viewed
{% for page in pages %}
- {{ page.url|truncate_dot:50|escape }}
- {{ page.url|truncate:50|escape }}
{% endfor %}
Not A Valid Tag Library
If you get the above error then try the following:
- Check that your load call in the template matches your templatetag filename.
- Make sure you put the code in a directory called "templatetags".
- Make sure you added a blank "__init__.py" file to your "templatetags" directory.
TemplateSyntaxError at /
'truncate_filter' is not a valid tag library: Could not load template library from django.templatetags.truncate_filter, No module named truncate_filter
Request Method: GET
Request URL: http://www.arkayne.com/
Exception Type: TemplateSyntaxError
Exception Value: 'truncate_filter' is not a valid tag library: Could not load template library from django.templatetags.truncate_filter, No module named truncate_filter
Exception Location: /somepath/lib/python2.4/django/template/defaulttags.py in load, line 692
More from Aware Labs
- Everything A Django Developer Needs To Create Logins
- Goodbye WebFaction Django Hosting – A Reflection
- Dynamic Length Truncate Tag
- UnicodeDecodeError Exception Fix On Templates
- Implementing CNN Style Votes In Django, Episode II
Aware Labs Recommends
- Popularizing Django — Or Reusable apps considered harmful. (USwaretech)
- Django’s tipping point (Antonio Cangiano)
- An Interview with Jacob Kaplan-Moss – Creator of Django (USwaretech)
-
pkenjora
-
pkenjora
-
tim
-
Malcolm Tredinnick
-
SuperJared
-
Mike
-
Vincent
-
Eric Florenzano
-
Eric Florenzano
-
Nathaniel Whiteinge
-
Orestis Markou
-
James Bennett

![Recommend [AwareLabs]](http://s3.amazonaws.com/arkayne-media/img/badge/logo-recommend-badge-medium.png)