Mat*_*ttG 19 javascript python django
我有一个由Django 中的views.py 生成的python 列表,我想将其传递给HTML 模板中的javascript。我似乎无法将其作为数组放入 javscript 中...我需要评估列表/数组是否包含某些数字,但它是以字符串的形式出现的。
我将列表传递到我的 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
Run Code Online (Sandbox Code Playgroud)
当我使用时:
<h1 id = "list"> {{mylist}}</h1>
Run Code Online (Sandbox Code Playgroud)
它在浏览器上显示为 [10,22,33,45]
然后在我的模板中我使用 javascript 我有:
var mylist = document.getElementById("list").innerHTML;
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
Run Code Online (Sandbox Code Playgroud)
这将返回到控制台:
'
[
1
0
,
2
2
........
Run Code Online (Sandbox Code Playgroud)
我想:
10
22
33
45
Run Code Online (Sandbox Code Playgroud)
我尝试在 python 中转换为 JSON,并在 javascript 中解析它,但似乎无法将此字符串转换为数组,或者不断收到错误。这里有什么最佳方法的想法吗?
Chr*_*ris 23
如果您绝对确定您的列表是安全的(我的意思是它永远不会包含用户输入的任何内容),那就非常简单。
在您看来:
context={"my_list": ["item1", "item2"]}
Run Code Online (Sandbox Code Playgroud)
在您的模板中:
{{ my_list|safe }}
Run Code Online (Sandbox Code Playgroud)
呈现为:
['item1', 'item2']
Run Code Online (Sandbox Code Playgroud)
例如:
{{ my_list|safe }}.forEach(item => {
console.log(item)
})
Run Code Online (Sandbox Code Playgroud)
令人印象深刻的是,如果您传递带有撇号的字符串,Django 会自动更改引号类型,因此
context = {"my_list": ["item1", "it'em2"]}
Run Code Online (Sandbox Code Playgroud)
呈现为(注意双引号):
['item1', "it'em2"]
Run Code Online (Sandbox Code Playgroud)
所以
{{ my_list|safe }}.forEach
Run Code Online (Sandbox Code Playgroud)
仍然有效(在 Django 3.2.6 上测试)。
即使这样也有效:
context = {"my_list": ["item1", "it'em\"2"]}
Run Code Online (Sandbox Code Playgroud)
呈现为:
['item1', 'it\'em"2']
Run Code Online (Sandbox Code Playgroud)
所以
{{ my_list|safe }}.forEach
Run Code Online (Sandbox Code Playgroud)
仍然有效。
但是,正如我在顶部所说,如果您的列表可能包含用户的输入,我仍然不会信任这种方法。
==
编辑:现在这是最高的答案,我想添加一种更安全的方法,以使其更容易完全安全。django-argonauts对此很感兴趣,尽管我不是安全专家,因此无法确认该方法:
@register.filter(is_safe=True)
def jsonify(json_object):
"""
Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter.
"""
json_str = json.dumps(json_object)
# Escape all the XML/HTML special characters.
escapes = ["<", ">", "&"]
for c in escapes:
json_str = json_str.replace(c, r"\u%04x" % ord(c))
# now it's safe to use mark_safe
return mark_safe(json_str)
Run Code Online (Sandbox Code Playgroud)
然后在模板中:
{% load jsonify %}
{{ value|jsonify }}
Run Code Online (Sandbox Code Playgroud)
小智 7
在视图中,您可以将对象设置为 JSON 对象:
import json
mylistraw = [10,22,33,45]
mylist = json.dumps(mylistraw)
context = {''mylistjson': mylist}
Run Code Online (Sandbox Code Playgroud)
现在您可以在 JavaScript 中使用您的对象:
var mylist = JSON.parse("{{mylistjson}}")
Run Code Online (Sandbox Code Playgroud)
对于您的情况,一种简单的方法是将列表作为 string 发送','.join(mylist)。然后在您的模板中,您可以简单地使用split(',')in js。
意见
mylist = [10,22,33,45]
context['mylist'] = ','.join([str(i) for i in mylist])
Run Code Online (Sandbox Code Playgroud)
html和js
var mylist = document.getElementById("list").innerHTML;
mylist = mylist.split(',')
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
Run Code Online (Sandbox Code Playgroud)
或者如果你的js也在模板中
var mylist = '{{mylist}}'.split(',');
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19958 次 |
| 最近记录: |