Pass a list of string from Django to Javascript Pass a list of string from Django to Javascript jquery jquery

Pass a list of string from Django to Javascript


When you do {{ city_array }} in your template, your list is converted to a string. This is done by calling repr() on the list, which recursively calls repr() on its contents. Because your strings are unicode, you see those unicode literals, u'Paris'.

The "correct" way to do this is to encode your data to json, for example in your view:

import json# ...json_cities = json.dumps(city_array)# ...return render (request, 'plot3/plot_page.html', {"city_array" : json_cities})

and then do

var cities = {{ city_array|safe }};

in the template.

Please note: don't use this for user-controller data! See the XSS Cheat Sheet by OSWASP and the discussion on Django ticket 17419 for further information. To prevent XSS, you could use something like the SafeJSONEncoder from the django-cms project.