首先,我要说@DNS的答案是正确的,为什么空格没有显示出来。
考虑到这一点,此模板过滤器会将字符串中的所有空格替换为
用法:
{{ "hey there world"|spacify }}
输出将是 hey there world
这是代码:
from django.template import Library
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import re
register = Library()
@stringfilter
def spacify(value, autoescape=None):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(re.sub('\s', '&'+'nbsp;', esc(value)))
spacify.needs_autoescape = True
register.filter(spacify)
有关模板过滤器如何工作以及如何安装的注释,请参阅docs。