Inline truncate by character number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django import template

register = template.Library()

@register.filter("inline_truncate")
def inline_truncate(value, size):
    """Truncates a string to the given size placing the ellipsis at the middle of the string"""
    if len(value) > size and size > 3:
        start = (size - 3) / 2
        end = (size - 3) - start
        return value[0:start] + '...' + value[-end:]
    else:
        return value[0:size]

More like this

  1. Truncate filter by zalun 4 years ago
  2. Truncate Characters Filter (simple) by leahculver 6 years, 1 month ago
  3. Truncate text to length up until the nearest space by phektus 2 years, 2 months ago
  4. Truncate words by characters by trodrigues 5 years ago
  5. truncatestring filter by pigletto 4 years, 2 months ago

Comments

Tarken (on November 13, 2008):

Exactly what I needed! Thanks a bunch

#

(Forgotten your password?)