Skip to content

Instantly share code, notes, and snippets.

@yinian1992
Last active December 25, 2015 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yinian1992/6987693 to your computer and use it in GitHub Desktop.
Save yinian1992/6987693 to your computer and use it in GitHub Desktop.
Proper truncate template filter considering char width
import unicodedata
from django import template
register = template.Library()
@register.filter
def truncate(text, max_length):
max_length = int(max_length) - 3
length = 0
wide_widths = ['F', 'W', 'A']
for i in range(len(text)):
if text[i] == '@' or text[i].isupper():
length += 2
elif unicodedata.east_asian_width(text[i]) not in wide_widths:
length += 1
else:
length += 2
if length == max_length:
return text[:i + 1] + '...'
if length > max_length:
return text[:i] + '...'
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment