Created
January 27, 2012 10:18
-
-
Save c4urself/1688155 to your computer and use it in GitHub Desktop.
Django truncate words by characters
This file contains hidden or 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
| 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