2011-04-10 72 views
12

我正在使用django消息,並且想要在其中放入超鏈接。在django消息中放入一個<a>超鏈接

view.py:

from django.contrib import messages 

def my_view(request): 
    messages.info(request,"My message with an <a href='/url'>hyperlink</a>") 

顯然,在我的網頁,我看到的HTML代碼,並沒有超鏈接。如何將消息視爲一個htlml代碼?

希望這是明確的。

+1

雖然這裏的答案都可以正常工作,我強烈建議提供一個非常類似的問題在這裏的答案:http://stackoverflow.com/a/10124845/26196 - 它提供了更多潛在的靈活性,而一些其他方法的注意事項。 – 2015-01-16 01:22:20

回答

10

Django模板中的字符串會自動轉義。你不希望你的原始HTML是自動逃跑,所以您應該在字符串傳遞給safe過濾器:

{{ message|safe }} 

或禁用autoescape與autoescape標籤:

{% autoescape off %} 
    {{ message }} 
{% endautoescape %} 
38

如果您不想關閉autoescaping上的所有消息/模板,你可以使用mark_safe該特定消息:

from django.utils.safestring import mark_safe 

messages.info(request, mark_safe("My message with an <a href='/url'>hyperlink</a>")) 

如果你也許有一些不安全的PA您的消息的rts可以使用cgi.escape來轉義這些部分。

from cgi import escape 
messages.info(request, mark_safe("%s <a href='/url'>hyperlink</a>" % escape(unsafe_value))) 
+0

你必須使用SessionStorage作爲消息框架才能工作 - 請參閱http://stackoverflow.com/questions/2053258/how-do-i-output-html-in-a-message-in-the -new-Django的消息的框架 – 2013-02-07 11:43:13