如何将Django中的数组传递给模板并将其与JavaScript一起使用

Chr*_*ian 40 javascript django django-templates

我想将一个数组传递给一个模板,然后通过JavaScript使用它.

在我的views.py中,我有:

arry1 = ['Str',500,20]
return render_to_response('test.html', {'array1': arry1})
Run Code Online (Sandbox Code Playgroud)

在我的模板中:

var array1 = {{ array1 }};
Run Code Online (Sandbox Code Playgroud)

但当我访问该网站时,它输出:

var array1 = ['Str',500,20];
Run Code Online (Sandbox Code Playgroud)

我需要改变什么?

Den*_*gan 80

尝试使用{{ array1|safe }},看看是否有任何区别.我没有对此进行过测试,所以我希望如果这是不正确的话我也不会太过低估


Bar*_*tek 17

如上所述,您可以使用|safe过滤器,因此Django不会清理数组并保持原样.

另一个选择,也许是长期更好的选择是使用simplejson模块(它包含在django中)将Python列表格式化为JSON对象,您可以在其中回吐Javascript.您可以像使用任何数组一样遍历JSON对象.

from django.utils import simplejson
list = [1,2,3,'String1']
json_list = simplejson.dumps(list)
render_to_response(template_name, {'json_list': json_list})
Run Code Online (Sandbox Code Playgroud)

在你的Javascript中,只是 {{ json_list }}

  • 也许最好的方法是使用simplejson.dumps,然后使用| safe filter? (2认同)
  • 自django 1.5使用json.dumps后删除simplejson.dumps http://stackoverflow.com/questions/28048943/cannot-import-name-simplejson-after-installing-simplejson (2认同)

小智 6

在Django:

from django.utils import simplejson
json_list = simplejson.dumps(YOUR_LIST)
Run Code Online (Sandbox Code Playgroud)

并在背景中传递"json_list"

IN JS:

var YOUR_JS_LIST = {{YOUR_LIST|safe}}; 
Run Code Online (Sandbox Code Playgroud)

  • 在 Django 1.5 之后,似乎 `simplejson` 不再可用。使用 Python 的 json 代替(`import json`) (2认同)