58

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?

Pebbl
  • 34,937
  • 6
  • 62
  • 64
Christian
  • 25,249
  • 40
  • 134
  • 225
  • Please, be more specific. How does this "obviously" break your code? The JavaScript looks valid to me. – Deniz Dogan Apr 11 '09 at 12:04
  • When I first posted the question stackoverflow reformatted & # 3 9 ; without the spaces to ' . I think it has to be ' to work as intended in the JavaScript (or at least I assume it to work that way. But somehow there appears & # 3 9 ; (again without the spaces) – Christian Apr 11 '09 at 12:22

6 Answers6

111

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

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162
  • particularly helpful to me (and others?) moving from App Engine Django ver 0.96 to ver 1.2: in ver 1.2 you HAVE to use the safe filter whereas is 0.96 it used to just work... – DanDan Oct 25 '11 at 20:38
  • What happens if one of elements in `array1` is datetime object. JavaScript doesn't recognize datetime. For example if `array1 = ['str', 500, 20, datetime.datetime(2017, 8, 23, 0, 0)]` – nishant Jan 05 '18 at 12:36
19

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

DarkCygnus
  • 7,420
  • 4
  • 36
  • 59
Bartek
  • 614
  • 1
  • 5
  • 15
  • 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 Apr 11 '09 at 12:59
  • 2
    Maybe the best way is to use simplejson.dumps and afterwards the |safe filter? – Christian Apr 11 '09 at 15:04
  • 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. – Bartek Apr 11 '09 at 15:55
  • 4
    simplejson.dumps removed since django 1.5 use json.dumps http://stackoverflow.com/questions/28048943/cannot-import-name-simplejson-after-installing-simplejson – amchugh89 Oct 29 '15 at 17:41
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}}; 
partlov
  • 13,789
  • 6
  • 63
  • 82
Tulio Nobrega
  • 91
  • 1
  • 1
  • 2
    It seems `simplejson` is no longer available beyond Django 1.5. Use Python's json instead (`import json`) – Anupam Sep 14 '17 at 20:08
0

It could be done by django core serializers. All you need to do is to serialize your data in json and than pass it to template.

data = serializers.serialize("json", <list>)
return render(request, 'view.html', {'data':data})

In your template save this list into javascript variable.

var list = {{data|safe}}
muak
  • 189
  • 2
  • 10
0

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Sanat Jha
  • 1
  • 2
  • 2
0

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.

Dimitrios Mistriotis
  • 2,626
  • 3
  • 28
  • 45