简体   繁体   English

如何转移python对象以在JavaScript变量中使用?

[英]How can I transfer a python object for use in a JavaScript variable?

I'm using Bottle and Python 2.7. 我正在使用Bottle和Python 2.7。

I would like to pass a list variable from my Bottle's controller to the view page, where it will be used in a JavaScript variable. 我想将列表变量从Bottle的控制器传递到视图页面,该页面变量将在JavaScript变量中使用。

@app.route('/foo'):
def foo():
    l = [{'name':'Matthew'}]
    return template('foo', l=l)

I've also done: 我也做了:

l = json.dumps([{'name':'Matthew'}]

In my view 在我看来

<script type="text/javascript">
    $(document).ready({
        var l = {{l}}
        l.forEach(function(entry) {
            console.log(entry);
        });
    });
</script>

However my console says I have a syntax error. 但是我的控制台说我有语法错误。 When I open the HTML, it is rendered like: 当我打开HTML时,它呈现为:

var l = [{&quot;name&quot;: &quot;Matthew&quot;]

How can I transfer a python object for use in a JavaScript variable? 如何转移python对象以在JavaScript变量中使用?

The substitutions between {{ and }} are HTML Entity encoded to prevent XSS amongst other things. {{}}之间的替换是HTML实体编码,以防止XSS等等。

Try this: 尝试这个:

var l = {{!l}};

Bottle (via, the SimpleTemplate engine) is escaping the output to prevent XSS vulnerability. Bottle(通过SimpleTemplate引擎)正在转义输出以防止XSS漏洞。 This is good, generally. 通常,这很好。 You can disable the escaping temporarily using ! 您可以使用暂时禁用转义! like: 喜欢:

var l = {{!l}};

The docs for it are here 它的文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM