Login

truncatechars filter

Author:
semente
Posted:
September 3, 2009
Language:
Python
Version:
1.1
Score:
3 (after 3 ratings)

Truncates a string after a certain number of chars.

Question:

Why don't you use the built-in filter slice?

I need the "three points" (...) only when it really truncates.

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

#

Please login first before commenting.