django模板过滤器删除html标记

django模板过滤器删除html标记,django,django-templates,django-template-filters,Django,Django Templates,Django Template Filters,在以下django模板变量中。是否可以通过django模板过滤器删除html标记 {{myvar|safe}} 下面将输出一个类似html的 <div>sddfdsfsdfsdf sd fsdf sd fsdf </div><a>This link</a><img src="some source" /> sddfdsfsdfsd fsdf sd fsdf sd fsdf此链接 你看过吗?它会将您的HTML转换成这样(当

在以下django模板变量中。是否可以通过django模板过滤器删除html标记

 {{myvar|safe}}
下面将输出一个类似html的

     <div>sddfdsfsdfsdf sd fsdf sd fsdf </div><a>This link</a><img src="some source" />
sddfdsfsdfsd fsdf sd fsdf sd fsdf此链接
你看过吗?它会将您的HTML转换成这样(当然,减去
this
的语法突出显示):

但是请注意,此模板过滤器使用一个,正则表达式在大多数情况下都不是处理HTML的正确工具。如果您的HTML来自外部,请确保使用真正的HTML解析器对其进行清理,例如..

striptags

尽一切努力剥离所有[X]HTML标记

例如:

{{ myvar|striptags }}
如果myvar是
Joel是slug
,则输出将是
Joel是slug

您还可以在python代码中使用strip_标记,例如在表单中

例如,在Form clean方法中:

class AddressForm(forms.ModelForm):

    class Meta:
        model = Address

    def clean(self):
        from django.utils.html import strip_tags
        cleaned_data = super(AddressForm, self).clean()
        cleaned_data['first_name'] = strip_tags(cleaned_data.get('first_name'))
        return cleaned_data

请参阅,也可以查看这个简单的。

要从现有字符串中剥离/删除HTML标记,我们可以使用剥离标记功能

导入strip_标记

from django.utils.html import strip_tags
包含html的简单字符串

html = '<p>paragraph</p>'

print html # will produce: <p>paragraph</p>
 

stripped = strip_tags(html)
print stripped # will produce: paragraph
如果只想删除特定的标签,则需要使用removetags

from django.template.defaultfilters import removetags
html = '<strong>Bold...</strong><p>paragraph....</p>'
stripped = removetags(html, 'strong') # removes the strong only.
stripped2 = removetags(html, 'strong p') # removes the strong AND p tags.
 

它去掉了所有标记,只在DOM speak中留下被认为是
TextNode
s的内容。我建议使用
{{myvar | striptags | safe}}
,这样像
这样的HTML实体就不会被Django转义,而是保存在HTML代码中并由web浏览器呈现。请注意,
striptags
过滤器实际上是剥离HTML标记,而不是实体。@Luca您能引用“实体”(相对于HTML标记)的含义吗?HTML实体是一系列数字或字符实体,用于编码标准ascii字符集以外的字符。这包括从符号到编码为
&;的所有内容至引号
&rdquo
&ldquoTemplate({{s | striptags}}}').render(s='script src='http://chezsoi.org“/”)
{{ somevalue|striptags }}
from django.template.defaultfilters import removetags
html = '<strong>Bold...</strong><p>paragraph....</p>'
stripped = removetags(html, 'strong') # removes the strong only.
stripped2 = removetags(html, 'strong p') # removes the strong AND p tags.
 
{{ value|removetags:"a span"|safe }}