我使用 djangos 模板过滤器 striptags .示例:
>>> 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.'
在段落之间添加空格字符的最佳方法是什么,以便我得到这个字符串:
'This is a paragraph. This is another paragraph.'
编辑:
我的一个想法是编写一个自定义模板过滤器来替换所有 </p>
带有 [space]</p>
的标签在 striptags
之前使用过滤器。但这是一个干净而强大的解决方案吗?
最佳答案
是的,对我来说这似乎是一个干净的解决方案。在尝试为 WagTail(基于 Django 构建)应用程序中的某些文章创建摘录时,我遇到了类似的问题。我在我的模板中使用了这个语法..
{{ page.body|striptags|truncatewords:50 }}
.. 并遇到与您描述的相同的问题。这是我提出的一个实现 - 希望对其他 Django/WagTail 开发人员也有用。
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)
然后你像这样使用它..
{{ page.body|excerpt:50 }}
关于python - Django strip_tags 模板过滤添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139455/