2014-05-08 16 views
1

我移植的傳統項目,Django和遇到了一個奇怪的數據庫狀態,已備案的內容已被HTML轉義:處理HTML轉義內容和編寫它作爲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,我不能我轉換轉義內容以流的HTML出去找這種格式:

<p> 

感謝

回答

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 %} 

,或者關掉autoescaping使用autoescape

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

我使用的第一格式{{object.field | unescape}},我得到的消息過濾器未定義...任何想法? – akaphenom

+0

@akaphenom是否已將'{%load ...%}'放到模板的頂部? – alecxe

+0

不,但我現在看到它在djanogo自定義模板標籤教程:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/我應該很快 – akaphenom