Login

truncate letters

Author:
trbs
Posted:
March 23, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

filter for truncating strings similar to truncatewords only with letters.

 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
27
28
from django import template

register = template.Library()

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

    Argument: Number of letters to truncate after
    """
    def truncate_letters(s, num):
        "Truncates a string after a certain number of letters."
        length = int(num)
        letters = [l for l in s]
        if len(letters) > length:
            letters = letters[:length]
            if not letters[-3:] == ['.','.','.']:
                letters += ['.','.','.']
        return ''.join(letters)

    try:
        length = int(arg)
    except ValueError: # invalid literal for int()
        return value # Fail silently
    if not isinstance(value, basestring):
        value = str(value)
    return truncate_letters(value, length)

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, 3 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, 7 months ago

Comments

simonbun (on March 23, 2007):

Why not rewrite this as:

@register.filter
def truncateletters(value, arg):
"""
Truncates a string after a certain number of letters

Argument: Number of letters to truncate after
"""

try:
    length = int(arg)
except ValueError: # invalid literal for int()
    return value # Fail silently
if not isinstance(value, basestring):
    value = str(value)

if len(value) > length:
    truncated = value[:length]
    if not truncated.endswith('...'):
        truncated += '...'
    return truncated

return value

#

trbs (on April 1, 2007):

yes :)

it's very rough and the inline function is not nice. have to try this out in my own app, surely your rewrite reads much better.

#

ershadul (on September 16, 2009):

when I will write truncateletters:20 , it means that I want to show atmost 20 letters. But the above code with add 3 dots if the length of the value is greater than 20. That is ultimate it will show 23 letters. I think one statement can be added after line no. 18 The code is:

  1. ....

letters = letters[:-3]

....

#

Please login first before commenting.