处理HTML转义内容并将其编写为HTML

时间:2014-05-08 19:43:08

标签: python html django django-templates escaping

我正在将一个遗留项目移植到django并遇到了一个奇怪的数据库状态,一个已被HTML转义的归档内容:

<p>
    <strong>The ‘Unbundling’ of Research is a secular, not cyclical, trend as it helps asset managers recognize and reward the value of research more independently</strong>.  In 2002, then-New York Attorney General Eliot Spitzer accused major investment banks of promoting companies' shares in their 

这样当我把它转储到djnago

<p>{{ object.field | safe }}</p>

然后再次转义输出:

&amp;lt;p&amp;gt;
真的很沮丧。我是djnago的新手,我无法将转义的内容转换为流式传输以获取此格式:

<p>

由于

1 个答案:

答案 0 :(得分:0)

您可以撰写custom unescape filter

from HTMLParser import HTMLParser    
from django import template   

register = template.Library()

@register.filter
def unescape(value):
    return HTMLParser().unescape(value)

这里是内部逻辑的演示:

>>> from HTMLParser import HTMLParser 
>>> value = '&lt;p&gt;'
>>> HTMLParser().unescape(value)
u'<p>'

以下是如何使用它:

<p>{{ object.field | unescape | safe }}</p>

或使用filter模板标记:

{% filter unescape|safe %}
    {{ value }}
{% endfilter %}

或使用autoescape关闭自动转义:

{% autoescape off %}
    {{ value | unescape }}
{% endautoescape %}