Last active
December 25, 2015 13:59
-
-
Save yinian1992/6987693 to your computer and use it in GitHub Desktop.
Proper truncate template filter considering char width
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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