Change: Passing Python Data to JavaScript

created on Dec. 5, 2012, 11:40 p.m. by Hevok & updated on Feb. 7, 2013, 10:42 a.m. by Hevok

Data can be passed from Python to JavaScript by dumping the Object into JSON and safe escaping it in the Template (py2js_):

.. sourcecode:: python

# views.py ... from django.shortcuts import render from django.utils import simplejson ... def view(request, template='graph.html'): network = { 'data': { 'nodes': [ {'id': '1', 'label': 'Concepts', 'text':'Denigma Concepts'}, {'id': '2', 'label': 'Aspects', 'text':'Three aspects'} ], 'edges': [ {'id': '2to1', 'label': 'belongs_to', 'text':'A belonging to relationship', 'target':'1', 'source': '2'} ] } } network_json = simplejson.dumps(network) return render(request, template, {'network_json': network_json}) ...

.. sourcecode:: js

// graph.html
...
<script type="text/javascript">
    ...
    data = {{ network_json|safe }};
    ...
</script>
...

.. _py2js: http://stackoverflow.com/questions/1445989/passing-python-data-to-javascript-via-django

json.gif

Categories: Tutorial, reST
Parent: Web Framework

Comment: Established links and corrected js sourcecode syntax.

See entry | Admin

Comment on This Data Unit