最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to read Python list in Javascript [in a Django template] - Stack Overflow

programmeradmin0浏览0评论

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

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!

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

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!

Share Improve this question edited Apr 11, 2017 at 4:02 RexE 17.7k16 gold badges62 silver badges85 bronze badges asked Jan 16, 2017 at 14:24 DenisDiderotDenisDiderot 571 silver badge9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

Your data should be JSON, instead of putting the Python list into the contact directly, put "array": json.dumps(array) in the context dictionary.

The JSON string doesn't need HTML escaping inside a tag, but it does need JS escaping! Otherwise some string may include something like </script><script>absolutely anything goes here... to run arbitrary JavaScript, if the JSON contains user data.

So use |escapejs:

var filtered_elements = {{ array|escapejs}};
发布评论

评论列表(0)

  1. 暂无评论