Reputation: 13682
Is there a way in django to strip the trailing spaces from a variable after it has been truncated using the truncate words filter? I.e. I do this:
{{post.body|safe|truncatewords:65}}
And end up getting something like this:
Foo foo foo foo foo foo foo foo ...
However I'd rather not have that trailing space. It should look like this:
Foo foo foo foo foo foo foo foo...
Is there a built in way to do this - I couldn't find one - or do I just need to make a custom filter?
EDIT:
For the record, if anyone else is having this issue, you will need to write a custom truncate function. As I was going about this I realized that django is probably making the "..." the final index in an array and joining it with a blank space. You will never be able to get rid of this without writing a custom filter!
Here's my implementation of truncate that does not put a space in between the last word and the ...:
In my template:
{{post.body|truncate:65|safe}}
In my templatetags package this:
@register.filter
@stringfilter
def truncate(value,end):
words = value.split()
keep = words[0:end]
keep[end-1] = keep[end-1]+"..."
return " ".join(keep)
It works! As you can see, it would have been easy to just make
keep[end] = "..."
Which is what I believe the truncatewords function probably does. But that doesn't look pretty because there will be white space before it when you join! So use this if you like!
Upvotes: 1
Views: 284