Skip to content

Instantly share code, notes, and snippets.

@akb
Created May 6, 2011 20:37
Show Gist options
  • Select an option

  • Save akb/959733 to your computer and use it in GitHub Desktop.

Select an option

Save akb/959733 to your computer and use it in GitHub Desktop.
truncatesmart template filter
from django import template
register = template.Library()
@register.filter
def truncatesmart(value, limit=80):
"""
Truncates a string after a given number of chars keeping whole words.
Usage:
{{ string|truncatesmart }}
{{ string|truncatesmart:50 }}
"""
try:
limit = int(limit)
# invalid literal for int()
except ValueError:
# Fail silently.
return value
# Make sure it's unicode
value = unicode(value)
# Return the string itself if length is smaller or equal to the limit
if len(value) <= limit:
return value
# Cut the string
value = value[:limit]
# Break into words and remove the last
words = value.split(' ')[:-1]
# Join the words and return
return ' '.join(words) + '...'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment