Reputation: 2669
I'm writing a small web application to display some data, which is currently stored as a dict
. I need to pass it to the template, but I keep on getting a javascript error: Unexpected identifier 'name'. Expected ';' after variable declaration.
The python code I'm using is:
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)
and the .tpl file is:
<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>
How do I ensure that the dict values are passed as strings, or are in some way useable by the js to do the displaying?
Ideally the format of the data used by the js should be:
var treeData = [{"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children":}]}]
Upvotes: 1
Views: 820
Reputation: 2592
first convert the dictionary into JSON. In this way, javascript on browser can read the data as an object.
Next, since the variable in template is name
, I think you should load the template with name as a argument. So overall the following should work on your end
import json
def hello():
....
my_data = {"name": "my name", "parent": "null", "children": "children"}
return template('tree', name=json.dumps(my_data))
Upvotes: 2