繁体   English   中英

如何用空格替换

[英]How to replace &nbsp with white space

我正在使用它来删除

{{i.content|truncatewords:30|striptags|safe|cut:" "}}

但是单词之间没有空格。

我要替换每个  与空白。

为此使用自定义过滤器

from django import template
from django.template.defaultfilters import stringfilter
import re

register = template.Library()

@register.filter(name='nbsp2space', is_safe=True)
@stringfilter
def nbsp2space(value):
    return re.sub(' ', ' ', value, flags=re.IGNORECASE)

像这样使用

{{i.content|truncatewords:30|striptags|safe|nbsp2space}}

注意: @register.filter(name='nbsp2space')使用提供的名称注册过滤器。 如果未提供名称,则使用函数的实际名称。 is_safe=True表示我们不会在值中引入不安全的字符。 @stringfilter确保参数始终是字符串。 re.sub()被用于str.replace()因为  可以是大写或小写, re.IGNORECASE会解决这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM