Django strip_tags template filter add space

别来无恙 提交于 2020-01-02 19:45:32

问题


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?


回答1:


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 }}


来源:https://stackoverflow.com/questions/40139455/django-strip-tags-template-filter-add-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!