对于Django用例,有两个答案。下面是它的django.utils.html.escape函数,供参考:def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&', '&').replace('
t;').replace('>', '>').replace('"', '"').replace("'", '''))
为了扭转这种情况,Jake的答案中描述的Cheetah函数应该可以工作,但是缺少一个引号。此版本包括一个更新的元组,其替换顺序是相反的,以避免出现对称问题:def html_decode(s):
"""
Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like
.
"""
htmlCodes = (
("'", '''),
('"', '"'),
('>', '>'),
('
('&', '&')
)
for code in htmlCodes:
s = s.replace(code[1], code[0])
return s
unescaped = html_decode(my_string)
然而,这不是一个通用的解决方案;它只适用于用django.utils.html.escape编码的字符串。更一般地说,最好还是使用标准库:# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)
# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)
建议:在数据库中存储未转义的HTML可能更有意义。如果可能的话,从美化组得到未美化的结果是值得研究的,并且完全避免这个过程。
对于Django,转义只在模板呈现期间发生;因此为了防止转义,只需告诉模板引擎不要转义字符串。为此,请在模板中使用以下选项之一:{{ context_var|safe }}
{% autoescape off %}
{{ context_var }}
{% endautoescape %}