smartTruncate.py 894 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. __author__ = 'pedroserrudo'
  2. __contanct__ = 'pedro@makeitdigital.io'
  3. from django import template
  4. from django.template.defaultfilters import stringfilter
  5. register = template.Library()
  6. @register.filter
  7. @stringfilter
  8. def smartcut(value, arg):
  9. """
  10. usage: description|smartcut:"20:30"
  11. 'this is a string text that will become smart truncated'|smartcut:'20:30' will become to
  12. 'this is a string text that...'
  13. normal truncate with 20 chars will cut the word in half
  14. 'this is a string tex...'
  15. """
  16. els = map(int, arg.split(':'))
  17. start = els[0]
  18. end = els[1]
  19. if len(value) <= end:
  20. return value
  21. ocurrence = value[start:end].find(" ")
  22. if ocurrence:
  23. for pos in range(start, len(value)):
  24. if value[pos] == " " and pos < end:
  25. ocurrence = pos
  26. value = value[0:ocurrence] + "..."
  27. return value