What would be the best way to pass a list from python to js using bottle?

怎甘沉沦 提交于 2019-12-06 05:47:38

问题


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.


回答1:


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}};



回答2:


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.




回答3:


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.




回答4:


In case of django use

var myNewList = {{myList|safe}};

Django doc



来源:https://stackoverflow.com/questions/11427417/what-would-be-the-best-way-to-pass-a-list-from-python-to-js-using-bottle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!