【问题标题】:Django view returns string which is not represented correctly in html templateDjango 视图返回在 html 模板中未正确表示的字符串
【发布时间】:2009-04-27 16:17:16
【问题描述】:

我正在使用的视图将字符串返回到 html 模板。返回的字符串包含在模板中未正确表示的特殊字符。简单地说,从视图返回的字符串可能如下所示:

test = "\"Foo bar\""
return render_to_response('index.html', {'test': test})

并且在html模板中是这样显示的:

& quot;Foo bar& quot;

如何修复编码以使其正确显示?

【问题讨论】:

    标签: django templates view


    【解决方案1】:

    打印时使用safe filter

    {{ test|safe }}
    

    或者,在视图中执行此操作:

    from django.utils.safestring import mark_safe
    test = mark_safe("\"Foo bar\"")
    

    请注意,这样做是在告诉 Django,字符串的内容是安全的,不需要 HTML 转义。如果您打算放置任何可能来自用户的内容,那么这将使您容易受到 XSS 攻击,因此请谨慎使用。

    【讨论】:

      【解决方案2】:

      最好的办法是查阅 Django 文档,其中详细解释了这一点:

      https://docs.djangoproject.com/en/2.0/ref/templates/language/#automatic-html-escaping

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        • 2014-09-09
        • 2019-10-28
        • 2016-08-21
        • 2011-02-02
        • 1970-01-01
        相关资源
        最近更新 更多