用瓶子将一个列表从Python传到js的最好方法是什么?[英] What would be the best way to pass a list from python to js using bottle?

本文是小编为大家收集整理的关于用瓶子将一个列表从Python传到js的最好方法是什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我将瓶子用作网络服务器,需要将python列表传递给JavaScript.

当我只做{{myList}}时,瓶子逃脱了列表中字符串的单引号,并将其显示为' 反过来,JS对它的收益不满意.

我设法找到了一个解决方案,但我认为这不是最佳的解决方案.

var tempList = '{{eval(myList)}}'.replace(/'/g, "'");
var myNewList = eval(tempList);

我想知道,有更好的方法吗?

upd:我将发现的解决方案移至"答案"部分.

推荐答案

我开始使用JSON(python3中的json_dumps,SimpleJson不会安装),但是Botter仍在逃脱单语引号.我在瓶子手册中发现您可以使用感叹号跳过逃脱并更改我的代码:

var myNewList = {{!myList}};

其他推荐答案

使用 json module 而不是;它毕竟输出有效的JavaScript表达式.

JSON(JavaScript对象符号)是JavaScript语法的子集(ECMA-262 3rd Edition)[…]

快速示例:

>>> import json
>>> json.dumps([1, 2, 'foo', 'bar'])
'[1, 2, "foo", "bar"]'

将该直接放入模板中.我一直在使用它将有效的JavaScript数据结构始终放入我生成的网页中.

其他推荐答案

我不熟悉瓶子,但是使用Django时我确实有同样的问题.我的解决方案是将Python列表转到JSON格式. JavaScript对Json感到满意.

myList = [1, 2, 3, 'string', "&apm;", '"']

然后将simplejson.dumps(myList)返回到您的网页. 在JS中:

var myList = <dumped-literal-JSON-string>

注意:不要用引号包围扬起的JSON值.

本文地址:https://www.itbaoku.cn/post/690292.html

问题描述

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 &#039; 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(/&#039;/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.