针对一些用户输入的情况,例如用户评论等,经常需要考虑去除其中的HTML标签。在Django中有很多方法,并且都很简单。
import the strip_tags
from django.utils.html import strip_tags
>>> html = '<p>paragraph</p>'
>>> print html
'<p>paragraph</p>'
>>> stripped = strip_tags(html)
>>> print stripped
'paragraph'
在Djanog模板中,可以利用以下方法去除:
{{ somevalue|striptags }}
以上方法会去除所有的HTML标签,如果只想去除几个特定的标签,则需要使用另一种方法实现:
>>> 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 }}