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})
var array1 = {{ array1 }};
but when I visit the website it puts out:
var array1 = [_39;Str_39;,500,20]; (without the _ sign (otherwise stackoverflow changes the formatting) with which obviously breaks my code and doesn't work as intended.
What do I have to change?
-
Try using
{{ array1|safe }}
and see if that makes any difference. I haven't tested this, so I hope I don't get too downvoted if this is incorrect... -
As mentioned, you could use the |safe filter so Django doesn't sanitize the array and leaves it as is.
Another option, and probably the better one for the long term is to use the simplejson module (it's included with django) to format your Python list into a JSON object in which you can spit back to the Javascript. You can loop through the JSON object just like you would any array really.
from django.utils import simplejson
list = [1,2,3,'String1']
json_list = simplejson.dumps(list)
render_to_response(template_name, {'json_list': json_list})
And in your Javascript, just {{ json_list }}
Christian : json_list becomes [1, 2, 3, & q u o t ;String1& q u o t ;] (I added the spaces after &,q,u,o,t to prevent stackoverflow from reformating the output) That also doesn't seem to work.Christian : Maybe the best way is to use simplejson.dumps and afterwards the |safe filter?Bartek : You're right, you'd still need to use |safe in this case. Normally when I do JSON with Django I fetch it using an AJAX method (like $.getJSON from jQuery) so I never deal with having to use |safe.