locoboy
locoboy

Reputation: 38960

Passing an array in Python to Django template

Let's say that I had an array in the Python backend and wanted to pass it to the front end as json or a js array. How would I be able to do this using the Django framework?

This is what the template might look like:

<script type="text/javascript">
var array = {{djangoVariable}};
//use the array somehow
</script>

Upvotes: 0

Views: 5037

Answers (5)

Tulio Nobrega
Tulio Nobrega

Reputation: 91

In Django:
from django.utils import simplejson
json = simplejson.dumps(YOUR_VARIABLE)

AND PASS "json" IN CONTEXT

IN JS:
var YOUR_JS_OBJECT = {{json|safe}};

Upvotes: 2

I try the answer, but the think that work by me was like:

in the view.py

from django.shortcuts import render_to_response
from django.utils import simplejson


def example_view(request):
   variable = {"myvar":[1, 2, 3]}
   render_to_response("example.html", simplejson.dumps(variable),
            context_instance=RequestContext(request))

And in the example.html

...
<script type="text/javascript">
        var myvar = "{{ myvar|safe }}";
</script>
...

Upvotes: 3

Francis Yaconiello
Francis Yaconiello

Reputation: 10939

Full view so you get the idea:

from django.shortcuts import render_to_response
from django.core import serializers

def my_view(request) :
    json_data = serializers.serialize('json', my_django_object)
    render_to_response('my_template.html', {'json_data' : json_data})

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599956

In your view:

js_variable = simplejson.dumps(django_variable)

and pass js_variable to your template in the normal way.

Upvotes: 0

F&#225;bio Diniz
F&#225;bio Diniz

Reputation: 10363

Maybe you should read a django tutorial on how to pass variables from python to the template.

BUT

If your python list is a list of numbers, you could just use str or the module simplejson on it that it would be already a javascript array to use in your template.

For example:

in your views.py:

import simplejson
def example_view(request)
   variable = [1, 2, 3]
   return render(request, 'example.html', {'djangoVariable': simplejson.dumps(variable)})

Upvotes: 0

Related Questions