以数组的形式访问javascript中的python列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23038710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing python list in javascript as an array
提问by knk
I have this in my flask views.py
我的烧瓶 views.py 中有这个
def showpage():
...
test = [1,2,3,4,5,6]
return render_template("sample.html",test=test)
I have this in my sample .html
我的示例 .html 中有这个
<script> var counts = {{test}}; </script>
This gives me a empty counts variable. How can I get the counts same as the test list in python?
这给了我一个空的计数变量。如何获得与python中的测试列表相同的计数?
采纳答案by tbicr
When you insert variable to template
{{ test }}
it take object representation. For list of int[1,2,3,4,5,6]
it will be rendered as[1, 2, 3, 4, 5, 6]
, so it is valid javascript array, but this method not safe complex objects without javascript-like representation, for example, test = [1,2,3,4,5,any] will rendered as[1, 2, 3, 4, 5, <built-in function any>]
, however this is just example and will never work.To implicitly cast to javascript object in flask exist
tojson
filter:<script> var counts = {{ test|tojson }}; </script>
So if the object is JSON serializable, then all will be rendered, otherwise the template engine will raise an exception.
You also can send javascript code to your template:
from flask import json return render_template("sample.html",test=json.dumps(test))
but it is not a good approach and it's better use
tojson
filter that is also HTML markup safe.I prefer to not mix any javascript code within templates and split templates, javascript and javascript data with ajax. If this approach is hard I would prefer to use
tojson
filter.
当您将变量插入模板时,
{{ test }}
它采用对象表示。对于 int 列表,[1,2,3,4,5,6]
它将呈现为[1, 2, 3, 4, 5, 6]
,因此它是有效的 javascript 数组,但是此方法在没有类似 javascript 的表示的情况下不安全的复杂对象,例如, test = [1,2,3,4,5,any] 将呈现as[1, 2, 3, 4, 5, <built-in function any>]
,但是这只是示例,永远不会起作用。要隐式转换为 Flask 中的 javascript 对象存在
tojson
过滤器:<script> var counts = {{ test|tojson }}; </script>
所以如果对象是JSON可序列化的,那么所有的都会被渲染,否则模板引擎会抛出异常。
您还可以将 javascript 代码发送到您的模板:
from flask import json return render_template("sample.html",test=json.dumps(test))
但这不是一个好方法,最好使用
tojson
也是 HTML 标记安全的过滤器。我不喜欢在模板和拆分模板中混合任何 javascript 代码,javascript 和 javascript 数据与 ajax。如果这种方法很难,我宁愿使用
tojson
过滤器。
回答by shaktimaan
You use json.dumpsin the flask view and JSON.parsein the javascript code.
您在flask 视图中使用json.dumps,在javascript 代码中使用JSON.parse。
In the python view:
在python视图中:
def showpage():
...
test = [1,2,3,4,5,6]
test = json.dumps(test)
return render_template("sample.html",test=test)
In the JavaScript code:
在 JavaScript 代码中:
<script> var counts = JSON.parse("{{ test }}"); </script>
回答by ziggerman
You can also use
你也可以使用
{{ test|safe }}
or
或者
{{ test|tojson|safe }}
The safe
filter is to be used within script tags.
该safe
过滤器应用到script标签内使用。
回答by Snehal Parmar
You try to return dictionary from your python showpage function like following and it will work:
您尝试从您的 python showpage 函数返回字典,如下所示,它将起作用:
def showpage():
"""Your logic for getting the list to return """
test_dict = {"data_list": [1,2,3,4,5]}
return render_template("sample.html", test=test_dict)
回答by Ryan Loggerythm
I've never liked having to use json.dumps
. In this solution, arrays are not a special case. Just put your arrays and any other variable into an object:
我从不喜欢必须使用json.dumps
. 在这个解决方案中,数组不是特例。只需将您的数组和任何其他变量放入一个对象中:
Python
Python
@app.route('/somePath')
def example():
data = {
'robotNames': ['Wall-E', 'Bender', 'Rosie']
}
return render_template('index.html', data=data)
JavaScript
JavaScript
<script>
var flaskData = JSON.parse('{{data | tojson | safe}}');
var robots = flaskData.robotNames;
robots.forEach(function (robot) {
console.log(robot);
});
</script>