Reputation: 38960
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
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
Reputation: 41
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
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
Reputation: 599956
In your view:
js_variable = simplejson.dumps(django_variable)
and pass js_variable
to your template in the normal way.
Upvotes: 0
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