Skip to content

Instantly share code, notes, and snippets.

@c4urself
Created January 27, 2012 10:18
Show Gist options
  • Select an option

  • Save c4urself/1688155 to your computer and use it in GitHub Desktop.

Select an option

Save c4urself/1688155 to your computer and use it in GitHub Desktop.
Django truncate words by characters
from django import template
register = template.Library()
@register.filter
def truncatewords_by_chars(value, arg):
"""
Truncate words based on the number of characters
based on original truncatewords filter code
Receives a parameter separated by spaces where each field means:
- limit: number of characters after which the string is truncated
"""
from django.utils.text import truncate_words
try:
limit = int(arg)
except ValueError: # Invalid literal for int().
return 'Invalid literal for int().'
if len(value) > limit:
while True:
words = value.split()
if len(words) > 1:
value = truncate_words(value, len(words)-2)
else:
value = value[0:limit]
if len(value) <= limit:
break
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment