Alex Rivera | Logout

How to pass an array in Django to a template and use it with JavaScript

Asked 2009-04-11T12:02:06.533
60

I want to pass an Array to a template and afterwards use it via JavaScript.

In my views.py I have:

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

And in my template:

var array1 = {{ array1 }};

but when I visit the website it outputs:

var array1 = ['Str',500,20];

What do I have to change?

Edit
Report

2 Answers

115

Try using {{ array1|safe }} and see if that makes any difference.

answered 2009-04-11T12:22:38.403
7

In Django:

from django.utils import simplejson
json_list = simplejson.dumps(YOUR_LIST)

AND PASS "json_list" IN CONTEXT

IN JS:

var YOUR_JS_LIST = {{YOUR_LIST|safe}}; 
answered 2013-01-25T20:47:12.017

Your Answer