Login

Precise truncate chars filter

Author:
davmuz
Posted:
January 20, 2012
Language:
Python
Version:
1.3
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.