1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from django.template import Library
register = Library()
@register.filter
def truncatewords_by_chars(value, arg):
"""Truncate the text when it exceeds a certain number of characters.
Delete the last word only if partial.
Adds '...' at the end of the text.
Example:
{{ text|truncatewords_by_chars:25 }}
"""
try:
length = int(arg)
except ValueError:
return value
if len(value) > length:
if value[length:length + 1].isspace():
return value[:length].rstrip() + '...'
else:
return value[:length].rsplit(' ', 1)[0].rstrip() + '...'
else:
return value
|
More like this
- Template filter that divides a list into exact columns by davmuz 1 year, 4 months ago
- truncate letters by trbs 6 years, 2 months ago
- Lorem ipsum -> Karel ende Elegast by Wicher 2 years, 2 months ago
- Truncate words by characters by trodrigues 5 years ago
- Truncate string after a given number of chars keeping whole words by rix 4 years, 5 months ago
Comments