Gui*_*mas 18 django django-templates
我正在使用django消息,我想在其中添加一个超链接.
view.py:
from django.contrib import messages
def my_view(request):
messages.info(request,"My message with an <a href='/url'>hyperlink</a>")
Run Code Online (Sandbox Code Playgroud)
显然,在我的页面中,我看到了html代码,没有超链接.如何将消息视为htlml代码?
希望这很清楚.
小智 49
如果您不想关闭所有消息/模板上的自动加载,则可以对该特定消息使用mark_safe:
from django.utils.safestring import mark_safe
messages.info(request, mark_safe("My message with an <a href='/url'>hyperlink</a>"))
Run Code Online (Sandbox Code Playgroud)
如果您的消息中有一些不安全的部分,您可以使用cgi.escape来逃避这些部分.
from cgi import escape
messages.info(request, mark_safe("%s <a href='/url'>hyperlink</a>" % escape(unsafe_value)))
Run Code Online (Sandbox Code Playgroud)
mip*_*adi 14
Django模板中的字符串会自动转义.您不希望自动转义原始HTML,因此您应该将字符串传递给safe过滤器:
{{ message|safe }}
Run Code Online (Sandbox Code Playgroud)
或使用autoescape标记禁用autoescape :
{% autoescape off %}
{{ message }}
{% endautoescape %}
Run Code Online (Sandbox Code Playgroud)
从https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.html.format_html,另一种选择是使用format_html将使用转义(不安全的)参数,类似于逃逸模板系统.
from django.utils.html import format_html
messages.info(request, format_html("My {} <a href='/url'>{}</a>", some_text, other_text))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6528 次 |
| 最近记录: |