I am using Bottle as a web server and need to pass a python list to javascript.
When I am doing just {{myList}}, Bottle escapes single quotes for strings in the list and shows them as '
JS, in turn, isn't very happy with what it gets.
I managed to find a solution, but I don't think it's an optimal one.
var tempList = '{{eval(myList)}}'.replace(/'/g, "'");
var myNewList = eval(tempList);
I wonder, is there a better way to do this?
upd: I moved the solution I found into the 'Answers' section.
I started using json (json_dumps in Python3, simplejson won't install), but bottle was still escaping single quotes. I found in Bottle manual that you can skip escaping using the exclamation sign and changed my code:
var myNewList = {{!myList}};
Use the json
module instead; it outputs valid JavaScript expressions after all.
JSON (JavaScript Object Notation) is a subset of JavaScript syntax (ECMA-262 3rd edition) […]
Quick example:
>>> import json
>>> json.dumps([1, 2, 'foo', 'bar'])
'[1, 2, "foo", "bar"]'
Put that straight into your template. I use this all the time to put valid JavaScript data structures into my generated web pages all the time.
I am not familiar with Bottle, but I do have the same problem when using Django. My solution is dump the Python list to JSON format. Javascript is happy with JSON.
myList = [1, 2, 3, 'string', "&apm;", '"']
Then return simplejson.dumps(myList)
to your web pages.
In js:
var myList = <dumped-literal-JSON-string>
NOTE: DO NOT surround the dumpped JSON value with quotes.
In case of django use
var myNewList = {{myList|safe}};
Django doc