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)
我需要改变什么?
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 }}
小智 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)
归档时间: |
|
查看次数: |
38437 次 |
最近记录: |