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
- Stuff by NixonDash 1 month ago
- Add custom fields to the built-in Group model by jmoppel 3 months, 1 week ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 6 months, 3 weeks ago
- Python Django CRUD Example Tutorial by tuts_station 7 months, 1 week ago
- Browser-native date input field by kytta 8 months, 3 weeks ago
Why not rewrite this as:
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.