Created
          August 24, 2011 18:03 
        
      - 
      
- 
        Save vbmendes/1168713 to your computer and use it in GitHub Desktop. 
    truncate templatetag
  
        
  
    
      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.utils.safestring import SafeData, mark_safe | |
| from django.template import TemplateSyntaxError | |
| @register.filter | |
| def truncate(value, arg): | |
| """ | |
| Truncates a string after a given number of chars | |
| Argument: Number of chars to truncate after | |
| """ | |
| mark_safe_if_safe = lambda v: mark_safe(v) if isinstance(value, SafeData) else v | |
| try: | |
| length = int(arg) | |
| except ValueError: # invalid literal for int() | |
| raise TemplateSyntaxError, "truncate tag's arg needs to be an integer" | |
| if not isinstance(value, basestring): | |
| value = unicode(value) | |
| if (len(value) > length): | |
| while value[length] != u' ' and length > 0: | |
| length -= 1 | |
| return mark_safe_if_safe(value[:length] + u"...") | |
| return value | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment