Denigma
hevok @hevok December 5, 2012
Tutorial reST #conversion #django #js #rest

Passing Python Data to JavaScript

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

# views.py
...
from django.shortcuts import render
from django.utils import simplejson
...
def view(request, template='graph.html'):
      network = {
      'data': {
                 'nodes': [
                     {'id': '1', 'label': '[Concept](/blog/560/)s', 'text':'[Denigma Concepts](/blog/55/)'},
                     {'id': '2', 'label': '[Aspects](/blog/56/)', '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})
     ...

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