如何在Javascript [在Django模板中]阅读Python列表 [英] How to read Python list in Javascript [in a Django template]
问题描述
我在oTree编程(这是一个基于Django的社交实验环境),我有以下问题。我在Python中定义了一些列表,我想导入它们并在HTML模板中使用它们。如果我用HTML打印它我会设法看到它们没有任何问题,但是,一旦我需要在Javascript中使用它们,程序就无法读取它们并且列表元素的单引号在&安培;#39;
。
列表导入如下 var filtered_elements = {{array}};
。
I'm programming in oTree (which is a Django based environment for social experiments) and I have the following problem. I defined some lists in Python and I'd like to import them and use them in an HTML template. If I print them in HTML I manage to see them without any problem, however, once I need to use them in Javascript, the program fails to read them and the single quotes of the elements of the list are converted in '
.
The list is imported like this var filtered_elements = {{ array }};
.
我认为问题就在这里,因为JS无法使用它们。你有什么建议怎么做吗?我考虑过使用JSON,但由于我对编程很陌生,我无法理解它是否只是浪费时间或者有更简单的方法。
感谢您的回答!
I think the problem is exactly here, as JS cannot work with them. Do you have any suggestion on how to do that? I considered using JSON, but since I'm quite new to programming, I cannot understand if it's just a waste of time or there is a simpler way out. Thanks for your answers!
推荐答案
听起来您的数据已经是JSON,否则您将获得单引号和 u
前缀。所以唯一的问题是Django autoescaping;您可以使用 safe
过滤器禁用它:
It sounds like your data is already JSON, otherwise you would be getting single quotes and u
prefixes. So the only issue is Django autoescaping; you can disable it with the safe
filter:
var filtered_elements = {{ array|safe }};
这篇关于如何在Javascript [在Django模板中]阅读Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!