Truncates a string after a given number of chars
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from django import template
register = template.Library()
@register.filter
def truncate(value, arg):
"""
Truncates a string after a given number of chars
Argument: Number of chars 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):
return value[:length] + "..."
else:
return value
|
More like this
- find even number by Rajeev529 2 weeks, 1 day ago
- Form field with fixed value by roam 1 month ago
- New Snippet! by Antoliny0919 1 month, 1 week ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 4 months ago
- get_object_or_none by azwdevops 7 months, 3 weeks ago
Comments
Perfect timing...I thought I was going to have to write this today.
I ended up editing it slightly so that it only includes the ellipsis when the string is too long.
#
thanks, updated!
#
Please login first before commenting.