Django Template Tag for Truncating Characters at a Word Boundary

The default truncatechars template tag truncates a string if it is longer than the specified number of characters but does so exactly at the character count, irrespective of whether it’s the middle of a word or not.

Here’s a smarter version that clips the text at the word boundary:

from django import template
register = template.Library()
# truncate chars but leaving last word complete
def smart_truncate_chars(value, max_length):
if len(value) > max_length:
# limits the number of characters in value to max_length (blunt cut)
truncd_val = value[:max_length]
# check if the next upcoming character after the limit is not a space,
# in which case it might be a word continuing
if value[max_length] != ' ':
# rfind will return the last index where matching the searched character,
# in this case we are looking for the last space
# then we only return the number of character up to that last space
truncd_val = truncd_val[:truncd_val.rfind(' ')]
return truncd_val + '…'
return value

One thought on “Django Template Tag for Truncating Characters at a Word Boundary”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s