Django template filter strip_tags adds space

I use the djangos striptags template filter. Example:

>>> from django.utils.html import strip_tags >>> strip_tags("<p>This is a paragraph.</p><p>This is another paragraph.</p>") 'This is a paragraph.This is another paragraph.' 

What is the best way to add a space character between paragraphs to get this line instead:

 'This is a paragraph. This is another paragraph.' 

Edit:

One of my ideas is to write my own template filter that replaces all tags </p> [space]</p> before using the striptags filter. But is this a clean and reliable solution?

+1
python django django-templates
source share
1 answer

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().' # remove spaces between tags value = strip_spaces_between_tags(value) # add space before each P end tag (</p>) value = value.replace("</p>"," </p>") # strip HTML tags value = strip_tags(value) # other usage: return Truncator(value).words(length, html=True, truncate=' see more') return Truncator(value).words(limit) 

and you use it like that.

 {{ page.body|excerpt:50 }} 
+1
source share

All Articles