【问题标题】:Put a <a> hyperlink in a django message [duplicate]在django消息中放置一个<a>超链接[重复]
【发布时间】:2011-08-02 14:54:03
【问题描述】:

我正在使用 django 消息,我想在其中添加一个超链接。

view.py:

from django.contrib import messages

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

显然,在我的页面中,我看到了 html 代码并且没有超链接。如何将消息视为 html 代码?

希望这很清楚。

【问题讨论】:

  • 虽然这里的答案可行,但我强烈建议在此处为非常相似的问题提供答案:stackoverflow.com/a/10124845/26196——它提供了更大的潜在灵活性,而没有其他方法的一些警告。

标签: django django-templates


【解决方案1】:

Django 模板中的字符串会自动转义。您不希望原始 HTML 被自动转义,因此您应该将字符串传递给 safe 过滤器:

{{ message|safe }}

或使用autoescape 标签禁用自动转义:

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

【讨论】:

    【解决方案2】:

    如果您不想关闭所有消息/模板的自动转义,可以对特定消息使用 mark_safe:

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

    如果您的消息中可能有一些不安全的部分,您可以使用 cgi.escape 转义这些部分。

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

    【讨论】:

    • 您必须将 SessionStorage 用于消息框架才能使其正常工作 - 请参阅 stackoverflow.com/questions/2053258/…
    • 我想这不应该为每条消息启用,因为它们可能包含用户提供的数据,只是为了安全起见。谢谢你的回答
    【解决方案3】:

    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))
    

    【讨论】:

      猜你喜欢
      • 2015-08-10
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2011-10-17
      • 2016-06-22
      • 2022-01-06
      • 1970-01-01
      • 2018-11-28
      相关资源
      最近更新 更多