You want to insert a JavaScript array, not a Python list.
The easiest way to convert between Python and JavaScript formats is to use the json
module. JSON is a JavaScript subset for data after all:
import json
jsdata = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
then pass jsdata
to your template instead. The str.replace()
calls ensure that the data remains HTML safe.
In the template, interpolate this without escaping:
<script>
var data = ${structure:jsdata};
</script>