最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing an array in Python to Django template - Stack Overflow

programmeradmin1浏览0评论

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>

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>
Share Improve this question asked Aug 12, 2011 at 13:40 locoboylocoboy 39.1k73 gold badges188 silver badges263 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

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)

  1. 暂无评论