Django strip_tags模板过滤器添加空格 [英] Django strip_tags template filter add space
问题描述
我使用djangos模板过滤器 striptags 。示例:
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.'
编辑:
一个想法是写一个自定义模板过滤器,用 [space]< / p>替换所有
之前使用< / p>
striptags
过滤器。但是,这是一个干净,健壮的解决方案吗?
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?
推荐答案
是的,这似乎是一个干净的解决方案。当我尝试为WagTail(建立在Django)应用程序上的一些文章创建一个摘录时,我有一个类似的问题。我在我的模板中使用这种语法。
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 }}
..并得到您描述的相同问题。这是我提出的一个实现 - 希望对其他Django / WagTail开发人员有用。
.. 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 }}
这篇关于Django strip_tags模板过滤器添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!