Django has truncatewords template tag, which cuts the text at the given word count. But there is nothing like truncatechars.
What\'s the best w
If you prefer to create your own custom template tag, consider to use the Django util Truncator in it. The following is a sample usage:
>>> from django.utils.text import Truncator
>>> Truncator("Django template tag to truncate text")
at 0x10ff81b18>>
>>>Truncator("Django template tag to truncate text").words(3)
u'Django template tag...'
Truncator("Django template tag to truncate text").words(1)
u'Django...'
Truncator("Django template tag to truncate text").chars(20)
u'Django template t...'
Truncator("Django template tag to truncate text").chars(10)
u'Django ...'
Then you can put it in a template tag:
from django import template
from django.utils.text import Truncator
register = template.Library()
@register.filter("custom_truncator")
def custom_truncator(value, max_len, trunc_chars=True):
truncator = Truncator(value)
return truncator.chars(max_len) if trunc_chars else truncator.words(max_len)