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

Viewed 54950

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?

6 Answers

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

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 }}

Just Try replacing var array1 = {{ array1 }}; with var array1 = '{{ array1|safe }}'; . I dont know why but this worked for me. enter image description here

Not sure when it was added to Django, a candate for the same result is json-script:

{{ value|json_script:"hello-data" }}

If value is the dictionary {'hello': 'world'}, the output will be:

<script id="hello-data" type="application/json">{"hello": "world"}</script>

The resulting data can be accessed in JavaScript like this:

const value = JSON.parse(document.getElementById('hello-data').textContent);

ID, "hello-data" in the case above will be optional on Django versions after 4.0.

Related