将字典传递给模板

Passing a dictionary to a template

我正在编写一个小型 Web 应用程序来显示一些当前存储为 dict 的数据。我需要将它传递给模板,但我不断收到 javascript 错误:Unexpected identifier 'name'. Expected ';' after variable declaration.

我使用的 python 代码是:

from bottle import run
from bottle import template

app = Bottle()


@app.route("/hello")
def hello():
    # .... code to read and clean the data
    my_data = {"name": "my name", "parent": "null", "children": "children"}
    return template('tree', **my_data)


run(app, host='localhost', port=8080, debug=True)

.tpl 文件是:

 <body>

<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>

var treeData = {{!name}};

//some javascript to display the data

</script>
</body>
</html>

如何确保 dict 值作为字符串传递,或者以某种方式可由 js 用于显示?

理想情况下js使用的数据格式应该是:

var treeData =  [{"name": "Top Level",
"parent": "null",
"children": [
  {
    "name": "Level 2: A",
    "parent": "Top Level",
    "children":}]}]

首先将字典转换成JSON。这样,在浏览器上javascript就可以将数据作为一个对象来读取了。

接下来,由于模板中的变量是name,我认为您应该使用名称作为参数加载模板。所以总的来说,以下内容应该对你有用

import json
def hello():
     ....
     my_data = {"name": "my name", "parent": "null", "children": "children"}
     return template('tree', name=json.dumps(my_data))