Login

TruncateChars

Author:
Aveal
Posted:
October 13, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Usuage: {{ comment.comment|truncatechars:20 }}

Why to use: First of all, my english isn´t the best. I hope you will understand my text anyways :)

Ok, I had a problem with some "kiddies" posting huge comments like

"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaahhhhhhhhhhhhhhhhhhh this game rooooooooooocks!!!!!!!!!!!!!!!!".

Django has no function to "kill" that huge words within a string. So I´ve coded this little peace and hope that someone could use it.

Greets from Germany, Aveal

http://www.onlinewars.eu

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

#

Please login first before commenting.