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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Why not rewrite this as:
#
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.
#
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:
letters = letters[:-3]
....
#
Please login first before commenting.