Reputation: 668
I am struggling to move data from my tornado webserver to a javascript handsontable. I think the problem is related to escaping or encoding my data properly, but I can't figure it out.
Here's the python code. I am taking a list of lists and encoding it as json.
class hot_index(tornado.web.RequestHandler):
def get(self):
self.render("hot_tradedata.html",
data=json.dumps([
['', 'Tesla', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'],
['2017', 10, 11, 12, 13, 15, 16],
['2018', 10, 11, 12, 13, 15, 16],
['2019', 10, 11, 12, 13, 15, 16],
['2020', 10, 11, 12, 13, 15, 16],
['2021', 10, 11, 12, 13, 15, 16]
])
)
if __name__ == "__main__":
app = tornado.web.Application(
handlers=[(r"/hot", hot_index)],
static_path=os.path.join(os.path.dirname(__file__), "static"),
template_path=os.path.join(os.path.dirname(__file__), "templates")
Here's the handsontable code. I'd like the table to populate with the data I defined in my python function.
<div id="example1"></div>
<script>
var
data1 = {{data}},
container1 = document.getElementById('example1'),
settings1 = {
data: data1
},
hot1;
hot1 = new Handsontable(container1, settings1);
hot1.render();
</script>
The browser console indicates that the the data successfully was passed to the html page, but it looks like the javascript doesn't like the input. I think I need to escape the {{data}} differently?
<body><div id="example1"></div>
<script>
var
data1 = [["", "Tesla", "Nissan", "Toyota", "Honda", "Mazda", "Ford"], ["2017", 10, 11, 12, 13, 15, 16], ["2018", 10, 11, 12, 13, 15, 16], ["2019", 10, 11, 12, 13, 15, 16], ["2020", 10, 11, 12, 13, 15, 16], ["2021", 10, 11, 12, 13, 15, 16]],
container1 = document.getElementById('example1'),
settings1 = {
data: data1
},
hot1;
hot1 = new Handsontable(container1, settings1);
hot1.render();
</script>
Upvotes: 0
Views: 272
Reputation: 12577
By default Tornado "autoescapes" quotes. You can render it correctly using raw
function
<div id="example1"></div>
<script>
var
data1 = {% raw data %},
...
The other solution is to pass object (not json) to render and in the template use json_encode
. It looks cleaner I think, but it is not the case if you already have json string (eg. you received from other source) or you have large json and you want to use different(faster) implementation (like rapidjson, ujson) of json than json_encode
.
More info http://www.tornadoweb.org/en/stable/template.html#syntax-reference
Upvotes: 2