Yes, that seems like a clean solution to me. I had a similar problem when trying to create an excerpt for some articles in a WagTail application (based on Django). I used this syntax in my template.
{{ page.body|striptags|truncatewords:50 }}
.. and get the same problem that you described. Here is the implementation that I came up with - I hope it is useful for other Django / WagTail developers.
from django import template from django.utils.html import strip_spaces_between_tags, strip_tags from django.utils.text import Truncator register = template.Library() @register.filter(name='excerpt') def excerpt_with_ptag_spacing(value, arg): try: limit = int(arg) except ValueError: return 'Invalid literal for int().'
and you use it like that.
{{ page.body|excerpt:50 }}
robnardo
source share