Neil
Neil

Reputation: 3291

Django send data to Javascript in template

I want to make a very simple network graph for some links between documents that I've extracted, and display it in an existing Django application. I've looked at a bunch of Bokeh/Django integrations and things along those lines but nothing seems appropriate. Therefore I've decided to go ahead and try D3. I don't know any Javascript. I copied the template provided here: http://bl.ocks.org/mbostock/2706022 and this is fine for my purposes. All I need to do is to provide my own data. I can build up a list of dictionaries in the view and pass these as a context. I can access that context in the template with {{ data }}. However, what I don't know how to do is to then feed that to the javascript. This is the relevant part that I'll need to change:

var links = [
  {source: "Microsoft", target: "Amazon", type: "licensing"},
  {source: "Microsoft", target: "HTC", type: "licensing"},
  {source: "Samsung", target: "Apple", type: "suit"},
  {source: "Motorola", target: "Apple", type: "suit"},
  {source: "Nokia", target: "Apple", type: "resolved"},
...
  {source: "Nokia", target: "Qualcomm", type: "suit"}
];

This looks like a list of dictionaries. But I don't know, there's some bare words in there so I'm not sure how Javascript sees this thing and how to cast the python context into whatever this is. I imagine something along the lines of

var links = <cast>({{data}})

How do I implement this so that I can pass this D3 code my own data?

Upvotes: 0

Views: 517

Answers (1)

Cyrlop
Cyrlop

Reputation: 1984

You can build your list of dictionaries and pass it to your template as JSON.
Then parse your JSON string in javascript .

In python, use data = json.dumps(your_list_of_dict) and in javascript, use var links = JSON.parse('{{data}}');. You might need to do something more for the potential quotes issues.

Upvotes: 1

Related Questions