Reputation: 58781
I would like to pass dictionary data from Python into an index.html
. (I'm using tornado here, but am open to other small frameworks that allow it.)
I first serialize the data with json.dumps
, and this
def start_server():
data = {"a": 1, "b": 3}
string_data = json.dumps(data)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "web")
self.render(os.path.join(path, 'index.html'), data=string_data)
return
app = tornado.web.Application([(r"/", IndexHandler)])
app.listen(8000)
tornado.ioloop.IOLoop.current().start()
return
together with
<script>
console.log("{{data}}");
obj = JSON.parse("{{data}}");
console.log(obj);
</script>
in the index.html
gives me
{"a": 1, "b": 3}
Needless to say that JSON.parse
fails with those "
s.
Any hint on what's going wrong here?
Upvotes: 3
Views: 1157
Reputation: 5354
You should probably try {% raw data %}
. However, note that since you use the string inside a Javascript quoted string, 'data' itself should contain something suitable for that: and json.dumps() output is not valid - you'd need to escape it appropriately - either in the code that calls .render() or in the template itself (the latter is preferable). Maybe this:
obj = JSON.parse({% raw json_encode(data) %});
(using the fact that json_encode() of a string value will output "escaped-data")
Upvotes: 4