Created
May 6, 2011 20:37
-
-
Save akb/959733 to your computer and use it in GitHub Desktop.
truncatesmart template filter
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 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