简体   繁体   English

将 Django 中的列表作为数组放入 Javascript

[英]Getting a list from Django into Javascript as an array

I have a python list generated by my views.py in Django, and I would like to pass it to javascript in my HTML template.我有一个由 Django 中的 views.py 生成的 python 列表,我想将它传递给我的 HTML 模板中的 javascript。 I cannot seem to get it into javscript as an array... I need to evaluate if the list/array contains certain numbers, but it is coming over as a string.我似乎无法将它作为数组放入 javscript 中...我需要评估列表/数组是否包含某些数字,但它是作为字符串出现的。

I am passing the list to my HTML template like this:我将列表传递给我的 HTML 模板,如下所示:

def get_context_data(self, **kwargs):
    context = super(dashboardView, self).get_context_data(**kwargs)
    mylist = [10,22,33,45]
    context['mylist'] = mylist
    return context

When I use:当我使用:

<h1 id = "list"> {{mylist}}</h1>

it shows up on the browser as it shows up as [10,22,33,45]它显示在浏览器上,因为它显示为 [10,22,33,45]

Then in my template I am using javascript I have:然后在我的模板中我使用 javascript 我有:

var mylist = document.getElementById("list").innerHTML;
for(i = 0; i < mylist.length; i++){
    console.log(mylist[i])
};

this returns in the console:这在控制台中返回:

'
[
1
0
,

2
2
........

I want:我想要:

10
22
33
45

I have tried to convert to JSON in python, and parse it in javascript, but can't seem to convert this string to an array, or keep getting errors.我曾尝试在 python 中转换为 JSON,并在 javascript 中解析它,但似乎无法将此字符串转换为数组,或者不断出现错误。 Any ideas for the best method here?对这里最好的方法有什么想法吗?

You can simply use tojson tag to convert python list to js array.您可以简单地使用tojson标签将 python 列表转换为 js 数组。

It will be like -它会像——

var mylist = {{mylist|tojson}};
for(i = 0; i < mylist.length; i++){
    console.log(mylist[i])
};

Try it and let me know if any problem occurs.尝试一下,如果出现任何问题,请告诉我。

in views you just make your object as json object.在视图中,您只需将对象设为 json 对象。 the process is very simple.过程非常简单。

In Views:在视图中:

import json

mylistraw = [10,22,33,45]

mylist = json.dumps(mylistraw)

context = {''mylistjson': mylist}

now you can use your object in javascript.

var mylist = JSON.parse("{{mylistjson}}")

All the best!祝一切顺利!

In your case, a simple way is to send the list as string ','.join(mylist) .在您的情况下,一种简单的方法是将列表作为字符串','.join(mylist) And then in your templates, you could simply use split(',') in js .然后在你的模板中,你可以简单地在js使用split(',')

views意见

mylist = [10,22,33,45]
context['mylist'] = ','.join([str(i) for i in mylist])

html & js html 和 js

var mylist = document.getElementById("list").innerHTML;
mylist = mylist.split(',')
for(i = 0; i < mylist.length; i++){
    console.log(mylist[i])
};

Or in case your js is in the template as well或者如果您的 js 也在模板中

var mylist = '{{mylist}}'.split(',');
for(i = 0; i < mylist.length; i++){
    console.log(mylist[i])
};

If you are absolutely certain your list is safe, (by that I mean it never, ever includes anything entered by a user), it is very simple.如果您绝对确定您的列表是安全的(我的意思是它从不包括用户输入的任何内容),这非常简单。

In your view:在您看来:

context={"my_list": ["item1", "item2"]}

In your template:在您的模板中:

{{ my_list|safe }}

Renders as:呈现为:

['item1', 'item2']

For example:例如:

{{ my_list|safe }}.forEach(item => {
  console.log(item)
})

Impressively, if you pass a string with an apostrophe, Django automatically changes the quote types, so令人印象深刻的是,如果您传递带有撇号的字符串,Django 会自动更改引号类型,因此

context = {"my_list": ["item1", "it'em2"]}

renders as (note the double-quotes):呈现为(注意双引号):

['item1', "it'em2"]

so所以

{{ my_list|safe }}.forEach

still works (tested on Django 3.2.6).仍然有效(在 Django 3.2.6 上测试)。

Even this works:即使这有效:

context = {"my_list": ["item1", "it'em\"2"]}

renders as:呈现为:

['item1', 'it\'em"2']

so所以

{{ my_list|safe }}.forEach

still works.仍然有效。

However, as I said at the top, if your list might include input from a user, I still wouldn't trust this approach.但是,正如我在顶部所说,如果您的列表可能包含来自用户的输入,我仍然不会相信这种方法。

Django has the json_script template tag that addresses XSS vulnerabilities by escaping the < , > , and & characters. Django 有json_script模板标签,它通过转义<>&字符来解决 XSS 漏洞。

Django json_script docs here Django json_script文档在这里

Set the list value in JavaScript and not HTML.在 JavaScript 而不是 HTML 中设置列​​表值。

<script>
var mylist = {{mylist}};
for(i = 0; i < mylist.length; i++){
    console.log(mylist[i])
};
<\ script>

You need to do this in your HTML template file and not in an external JS file.您需要在 HTML 模板文件中执行此操作,而不是在外部 JS 文件中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM