Django の使用例を考えると、これには 2 つの答えがあります。参考までに、その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('<', '&l
t;').replace('>', '>').replace('"', '"').replace("'", '''))
これを逆にするには、Jake's answer で説明されている Cheetah 関数が機能するはずですが、一重引用符がありません。このバージョンには更新されたタプルが含まれており、対称的な問題を回避するために置換の順序が逆になっています。
def html_decode(s):
"""
Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>.
"""
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 をエスケープせずにデータベースに保存する方が理にかなっている場合があります。可能であれば、エスケープされていない結果を BeautifulSoup から取得し、このプロセスを完全に回避することを検討する価値があります。
Django では、エスケープはテンプレートのレンダリング中にのみ発生します。したがって、エスケープを防ぐには、テンプレート エンジンに文字列をエスケープしないように指示するだけです。これを行うには、テンプレートで次のオプションのいずれかを使用します。
{{ context_var|safe }}
{% autoescape off %}
{{ context_var }}
{% endautoescape %}