首页 > 解决方案 > 如何在 django 模板中删除 nbsp 并添加空间

问题描述

我需要在 django 模板中打印一个上下文变量....我的上下文变量名称“内容”

但是这个变量包含一些 html 标签和  ... 这是我的 html

<div style="max-width:800px;margin:50px auto;padding:0 12px">
    <div class="m_-1931231161305542174card" style="background:white;border-radius:0.5rem;padding:2rem;margin-bottom:1rem">
        {{ content }}
    </div>
</div>

例如我的用户正在输入这个

Hello,

How are you?

该上下文变量包含

<p>Hello,</p> <p>&nbsp;</p> <p>How are you??</p>

为了删除 html 标签,我返回了一个函数

我试过这个方法

def remove_html_tags(text):
    """Remove html tags from a string"""
    logger.info(text)
    clean = re.compile('<.*?>')
    return re.sub(clean, '', text)

def passing_contect(self):
-----------------
----------------------
-------------------)
context{'content':remove_html_tags(content)}//passing context without html tags

但 o/p 是

Hello, &nbsp; How are you ????

它仍然有这个   问题

如何处理

标签: djangodjango-templates

解决方案


在你的函数中试试这个:

def remove_html_tags(text):
    """Remove html tags and &nbsp from a string"""
    logger.info(text)
    clean = re.compile('<.*?>')
    sans_tags = re.sub(clean, '', text)
    return sans_tags.replace('&nbsp', ' ')

这将用实际空间替换空间。


推荐阅读