user2496550
user2496550

Reputation: 603

Django strip_tags template filter add space

I use djangos template filter striptags. 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 the paragraphs, so that I get this string instead:

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

Edit:

One idea I have is to write a custom template filter that replaces all </p> tags with [space]</p> before the striptags filter is used. But is that a clean and robust solution?

Upvotes: 4

Views: 3366

Answers (1)

robnardo
robnardo

Reputation: 931

yes, it seems like a clean solution to me. I had a similar issue when trying to create an excerpt for some articles in a WagTail (built on Django) application. I was using this syntax in my template..

{{ page.body|striptags|truncatewords:50 }}

.. and getting the same issue you described. Here is an implementation I came up - hopefully useful for other Django / WagTail developers as well.

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 this..

{{ page.body|excerpt:50 }}

Upvotes: 4

Related Questions