Reputation: 2189
I have myString = "Get the last nine characters of this text, starting with the last one."
and I want to be able to get the last nine characters of in Django template the way I could get the first nine with {{ myString|truncatechars:9 }}
.
Any idea on how I can get this done?
Upvotes: 0
Views: 276
Reputation: 221
You can write your own filters.
@register.filter("truncate_chars")
def truncate_chars(value, max_length):
if len(value) > max_length:
#will return last characters if max_length<0
truncd_val = value[max_length:]
if not len(value) == max_length+1 and value[max_length+1] != " ":
truncd_val = truncd_val[:truncd_val.rfind(" ")]
return truncd_val + "..."
return value
and then
{{ myString|truncate_chars:-9 }}
Upvotes: 1