Guest User

Untitled

a guest
Jul 18th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. def short_text(text, maxlength=200, endwith='...'):
  2. """
  3. Returns a shortened version of text up to maxlength long (not counting ending characters), breaking only on spaces to avoid weird looking summaries,
  4. and ending with endwith (default ellipsis written out with periods).
  5.  
  6. >>> short_text('ab cd ef gh', 9)
  7. 'ab cd...'
  8. >>> short_text('ab cd', 5)
  9. 'ab cd'
  10. >>> short_text('ab cd ef gh', 9, ':')
  11. 'ab cd ef:'
  12. """
  13.  
  14. if len(text) <= maxlength:
  15. return text
  16. return text[:maxlength - len(endwith) + 1].rpartition(' ')[0] + endwith
  17.  
  18. @register.filter('short_text')
  19. def short_text(text, length, autoescape=None):
  20. """
  21. makes short_text, breaking on words, length in characters rather than words like truncatewords
  22.  
  23. >>> short_text('some excessively long string', 21)
  24. 'some excessively...'
  25. >>> short_text('some excessively long string', 16) #don't forget the '...' counts!
  26. 'some...'
  27.  
  28. """
  29. return short_text(text, length)
  30. short_text.needs_autoescape = True
Add Comment
Please, Sign In to add comment