以数组的形式访问javascript中的python列表 [英] Accessing python list in javascript as an array
问题描述
我的flask views.py中有这个
I have this in my flask views.py
def showpage():
...
test = [1,2,3,4,5,6]
return render_template("sample.html",test=test)
我的示例 .html 中有这个
I have this in my sample .html
<script> var counts = {{test}}; </script>
这给了我一个空的计数变量.如何获得与python中的测试列表相同的计数?
This gives me a empty counts variable. How can I get the counts same as the test list in python?
推荐答案
当您将变量插入模板
{{ test }}
时,它采用对象表示.对于 int[1,2,3,4,5,6]
的列表,它将呈现为[1, 2, 3, 4, 5, 6]
,所以它是有效的 javascript 数组,但这种方法不安全没有类似 javascript 的表示的复杂对象,例如, test = [1,2,3,4,5,any] 将呈现为[1, 2, 3, 4, 5, <内置函数 any>]
,但这只是示例,永远不会起作用.
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.
要隐式转换为存在flask中的javascript对象tojson
过滤器:
To implicitly cast to javascript object in flask exist tojson
filter:
<script> var counts = {{ test|tojson }}; </script>
所以如果对象是JSON可序列化的,那么所有的都会被渲染,否则模板引擎会抛出异常.
So if the object is JSON serializable, then all will be rendered, otherwise the template engine will raise an exception.
您还可以将 javascript 代码发送到您的模板:
You also can send javascript code to your template:
from flask import json
return render_template("sample.html",test=json.dumps(test))
但这不是一个好方法,最好使用 tojson
过滤器,它也是 HTML 标记安全的.
but it is not a good approach and it's better use tojson
filter that is also HTML markup safe.
我不喜欢在模板和拆分模板中混合任何 javascript 代码,javascript 和 javascript 数据与 ajax.如果这种方法很难,我更愿意使用 tojson
过滤器.
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.
这篇关于以数组的形式访问javascript中的python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!