Precise truncate chars filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.template import Library

register = Library()

@register.filter
def truncatewords_by_chars(value, arg):
    """Truncate the text when it exceeds a certain number of characters.
    Delete the last word only if partial.
    Adds '...' at the end of the text.
    
    Example:
    
        {{ text|truncatewords_by_chars:25 }}
    """
    try:
        length = int(arg)
    except ValueError:
        return value
    
    if len(value) > length:
        if value[length:length + 1].isspace():
            return value[:length].rstrip() + '...'
        else:
            return value[:length].rsplit(' ', 1)[0].rstrip() + '...'
    else:
        return value

More like this

  1. truncate letters by trbs 7 years, 1 month ago
  2. Make a string a fixed-width by adamfast 6 years, 10 months ago
  3. Truncate filter by zalun 4 years, 12 months ago
  4. Word-boundary-aware string truncation template filter by josho 4 years, 11 months ago
  5. Truncate words by characters by trodrigues 5 years, 11 months ago

Comments

(Forgotten your password?)