truncatechars filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(name='truncatechars')
@stringfilter
def truncatechars(value, arg):
    """
    Truncates a string after a certain number of chars.

    Argument: Number of chars to truncate after.
    """
    try:
        length = int(arg)
    except ValueError: # Invalid literal for int().
        return value # Fail silently.
    if len(value) > length:
        return value[:length] + '...'
    return value
truncatechars.is_safe = True

More like this

  1. truncate by alfor 6 years, 1 month ago
  2. Truncate string after a given number of chars keeping whole words by rix 4 years, 4 months ago
  3. Truncate filter by zalun 4 years ago
  4. Precise truncate chars filter by davmuz 1 year, 4 months ago
  5. Truncate words by characters by trodrigues 5 years ago

Comments

sunn (on September 4, 2009):

An interesting feature would be if it only cuts whole words - like truncatewords but for chars (length then becomes the maximum length including ...)

#

allcaps (on September 4, 2009):

The interesting feature with a little problem.

Replace: return value[:length] + '...'

With: return value[:length].rsplit(" ", 1)[0] + ' ...'

>>> truncatechars("Hello World", 6)
'Hello ...'

If the length of the first word is greater or equal to arg, there is an undesirable space! >>> truncatechars("Hello World", 4) 'Hell ...'

#

rix (on September 4, 2009):

I did something similar, my solution keeps whole words, take a look:

Truncate string after a given number of chars keeping whole words

#

SmileyChris (on September 24, 2009):

See also, Django ticket #5025

#

(Forgotten your password?)