TruncateChars

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django import template
register = template.Library()

@register.filter
def truncatechars(s, num):
    """
    Truncates a word after a given number of chars  
    Argument: Number of chars to truncate after
    """
    length = int(num)
    string = []
    for word in s.split():
        if len(word) > length:
            string.append(word[:length]+'...')
        else:
            string.append(word)
    return u' '.join(string)

More like this

  1. CustomChoiceField, Selectable label field version of ModelChoiceField by mauro 6 years, 1 month ago
  2. Admin list thumbnail by theetderks 6 years, 11 months ago
  3. split filter by Ciantic 6 years, 11 months ago
  4. update-django: Update your django git branches. by telenieko 5 years, 5 months ago
  5. Use express.js like url patterns by ekinertac 1 year, 5 months ago

Comments

daevaorn (on October 13, 2007):

{{ comment.comment|slice:":20" }} ?

#

Aveal (on October 13, 2007):

@daevaorn

example: comment.comment = soooooooooome huuuuuuuge word

{{ comment.comment|slice:":5" }} = soooo

{{ comment.comment|truncatechars:5 }} = soooo... huuuu... word

#

ChrisRyland (on October 24, 2007):

Nice! This would probably be better named TruncateWords, no?

#

(Forgotten your password?)