Search code examples
pythontornado

tornado: pass string data to javascript code in a rendered page


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

{&quot;a&quot;: 1, &quot;b&quot;: 3}

Needless to say that JSON.parse fails with those &quots.

Any hint on what's going wrong here?


Solution

  • 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")