Login

Precise truncate chars filter

Author:
davmuz
Posted:
January 20, 2012
Language:
Python
Version:
1.3
Tags:
filter template-filter truncate truncatewords
Score:
0 (after 0 ratings)

Template filter that truncates the text when it exceeds a certain number of characters. It deletes the last word only if partial. Adds '...' at the end of the text, only if truncated.

Examples (text == 'Lorem ipsum dolor sit amet', len(text) == 26)

{{ text|truncatewords_by_chars:30 }}
'Lorem ipsum dolor sit amet'

{{ text|truncatewords_by_chars:25 }}
'Lorem ipsum dolor sit...'

{{ text|truncatewords_by_chars:21 }}
'Lorem ipsum dolor sit...'

{{ text|truncatewords_by_chars:20 }}
'Lorem ipsum dolor...'

By Davide Muzzarelli

 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 8 years ago
  2. Make a string a fixed-width by adamfast 7 years, 10 months ago
  3. Truncate filter by zalun 5 years, 11 months ago
  4. Word-boundary-aware string truncation template filter by josho 5 years, 11 months ago
  5. Truncate words by characters by trodrigues 6 years, 11 months ago

Comments

Please login first before commenting.