【问题标题】:Django how to turn a python string into a javascript string and render it to the websiteDjango如何将python字符串转成javascript字符串并渲染到网站上
【发布时间】:2022-01-02 02:29:44
【问题描述】:

我正在使用 Django,在我看来,我正在向我的页面发送 HTML 字符串:

 <p><code>202</code> </p><p>hello world/p>
<ul>
<li>Goodbye<strong><em>next</em></strong> or <strong><em>happy</em></strong> to go on.</li>
</ul> byebye <p>&lt;3</p>

但是,它被发送到页面:

    var html_smallest_steps =     
     &lt;p&gt;&lt;code&gt;202&lt;/code&gt; &lt;/p&gt;&lt;p&gt;hello world/p&gt;
&lt;ul&gt;
&lt;li&gt;Goodbye&lt;strong&gt;&lt;em&gt;next&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;happy&lt;/em&gt;&lt;/strong&gt; to go on.&lt;/li&gt;
&lt;

我的页面上出现控制台错误: Uncaught SyntaxError: Unexpected token '&amp;'

我的views.py是:

def displayDict(request):
    html_ss = 
""" 
    <p><code>202</code> </p><p>hello world/p>
    <ul> <li>Goodbye<strong><em>next</em></strong> or <strong><em>happy</em></strong> to go on. 
    </li> </ul> byebye <p>&lt;3</p>
    """
    return render(request, 'chatStream.html',
    {"html_sss": html_ss})

chatStream.html 是:

<p id="chatLine">get this working!!</p>

    <script>
    var html_smallest_steps = {{html_smallest_steps}}
    } 

setTimeout(myTimeout2, 2000) 

function myTimeout2() {
  document.getElementById("chatLine").innerHTML = "html_ss  " + html_ss;
}
</script>

【问题讨论】:

    标签: javascript python html django


    【解决方案1】:
    from django.utils.safestring import marksafe
    
    def displayDict(request):
        ...
        return render(request, 'chatStream.html',
        {"html_sss": mark_safe(html_ss)})
    

    或者您可以在模板中使用safe 标签。 https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatefilter-safe

    【讨论】:

    • 使用safe 是否被认为是一种不好的做法,因为它会使代码容易受到 XSS 攻击?
    • 谢谢@Daniel Kaminiski ...我现在能够导入marksafe ...由于某种原因而不是'&'的问题,我遇到了一个问题:Uncaught SyntaxError: Unexpected token '&lt;',其中var html_ss = &lt;p&gt;&lt;code&gt;202&lt;/code&gt; &lt;/p&gt;&lt;p&gt;hello world&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Goodbye&lt;strong&gt;&lt;em&gt;next&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;happy&lt;/em&gt;&lt;/strong&gt; to go on.&lt;/li&gt; &lt;/ul&gt; byebye &lt;p&gt;&amp;lt;3&lt;/p&gt; 好像把页面挂起来了
    • 好的,所以起作用的是使用 mark_safe() 并在字符串的开头和结尾添加 \".....\" 引号。浏览器将字符串呈现为 javascript 中的代码
    猜你喜欢
    • 1970-01-01
    • 2012-02-17
    • 2012-06-21
    • 1970-01-01
    • 2020-03-03
    • 2013-02-09
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多