在下面的django模板变量.Is中,可以通过django模板过滤器删除html标记
{{myvar|safe}}
以下代码将输出如下所示的html
<div>sddfdsfsdfsdf sd fsdf sd fsdf </div><a>This link</a><img src="some source" />
发布于 2011-07-07 15:00:16
你看过striptags
吗?它会把你的超文本标记语言变成这样(当然,去掉了This
的语法突出显示):
sddfdsfsdfsdf sd fsdf sd fsdf This link
但请注意,此模板过滤器使用regex来剥离HTML标记。在大多数情况下,正则表达式不是处理As we know的正确工具。如果你的超文本标记语言来自外部,请确保使用真正的超文本标记语言解析器对其进行清理,例如lxml.html.clean
。
发布于 2015-01-22 15:29:50
striptags
尽一切可能剥离所有XHTML标记。
例如:
{{ myvar|striptags }}
如果Joel is a slug
为<b>Joel</b> <button>is</button> a <span>slug</span>
,则输出为myvar。
你也可以在你的python代码中使用strip_tags。
例如,在表单清理方法中:
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
请参阅Django HTML Utils,也可以查看这个简单的Django HTML Sanitizer App。
发布于 2021-03-13 15:44:12
要从现有字符串中剥离/删除HTML标记,我们可以使用strip_tags函数。
导入strip_tags
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
这也可以作为模板标签使用:
{{ somevalue|striptags }}
如果只想删除特定的标记,则需要使用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.
在模板中也可用:
{{ value|removetags:"a span"|safe }}
https://stackoverflow.com/questions/6606866
复制相似问题