1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 | from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter(name='truncatechars')
@stringfilter
def truncatechars(value, arg):
"""
Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
if len(value) > length:
return value[:length] + '...'
return value
truncatechars.is_safe = True
|
Comments
An interesting feature would be if it only cuts whole words - like truncatewords but for chars (length then becomes the maximum length including ...)
#
#
I did something similar, my solution keeps whole words, take a look:
Truncate string after a given number of chars keeping whole words
#
See also, Django ticket #5025
#