开发者

Passing an array in Python to Django template

开发者 https://www.devze.com 2023-03-28 05:02 出处:网络
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 woul开发者_如何学运维d I be able to do this using the Django framework?

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 woul开发者_如何学运维d 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>


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


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


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


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


In your view:

js_variable = simplejson.dumps(django_variable)

and pass js_variable to your template in the normal way.

0

精彩评论

暂无评论...
验证码 换一张
取 消