Jack123321
Jack123321

Reputation: 57

Django - passing python data to javascript

I have a javascript code in my js.html:

{% load static %}
<script src="{% static  "vis.js" %}"></script>

<div id="mynetwork"></div>
<script type="text/javascript">

  var nodes = new vis.DataSet([
    {'id': 1, 'label': 'node 1'},
    {'id': 2, 'label': 'node 2'},
    {'id': 3, 'label': 'node 3'},
    {'id': 4, 'label': 'node 4'},
    {'id': 5, 'label': 'node 5'}
  ]);

  var edges = new vis.DataSet([
    {'from': 1, 'to': 3},
    {'from': 1, 'to': 2},
    {'from': 2, 'to': 4},
    {'from': 2, 'to': 5},
    {'from': 3, 'to': 3}
  ]);

  var container = document.getElementById('mynetwork');
  var data = {
    nodes: nodes,
    edges: edges
  };
  var options = {};
  var network = new vis.Network(container, data, options);
</script>

I have a python variable called nodesJS which takes this form when printed:

[{'id': 1, 'label': 'node 1'},
    {'id': 2, 'label': 'node 2'},
    {'id': 3, 'label': 'node 3'},
    {'id': 4, 'label': 'node 4'},
    {'id': 5, 'label': 'node 5'} ]

which is the same form that this javascript would use. In my views.py i'm just passing nodesJS variable in a context. Now i wanted to write my js code in this style:

var nodes = new vis.DataSet({{nodesJS}});

And the problem is that it doesn't work. Is there any way for js to treat my python variable the i want it to?

Upvotes: 0

Views: 305

Answers (1)

Borut
Borut

Reputation: 3364

You can use safe tag - {{ nodeJS|safe }}.

[Safe] marks a string as not requiring further HTML escaping prior to output.

Upvotes: 1

Related Questions