I want to use the JavaScript InfoVis Tooljit ( http://thejit.org ) to render a tree of mptt nodes in django. How can i create the required json structure (see http://thejit.org/static/v20/Jit/Examples/Spacetree/example1.code.html for an example) in django?
Thanks
If you use the template functionality of django-mptt to generate the JSON data you should be able to do something like the following:
var json =
{% recursetree nodes %}
{
id: "{{ node.id }}",
name: "{{ node.name }}",
data: {},
children: [{{ children }}]
},
{% endrecursetree %}
The children tag is brilliant, basically calling recursetree for each child of the node. However there is a little messiness generated around commas with this solution as the mptt example is around list elements where such things aren't a problem.
A slightly larger bit of code solves this:
var json =
{
id: "{{ root.id }}",
name: "{{ root.name }}",
data: {},
children: [{% recursetree root.children %}
{
id: "{{ node.id }}",
name: "{{ node.name }}",
data: {},
children: [{{ children }}]
}
{% endrecursetree %}]
}
By making a distinction between the root node (presuming there is only one) which does not reside within an array but is instead assigned to a variable, compared to other nodes which live within the children of another node, the var x = y,
issue is avoided.
There is still a problem with children: [x,y,z,]
having a trailing comma. If that final comma is raising errors then in the view that has called the template you can always do a quick string replace to replace ,]
with ]
Alternatively you could alter the {{ children }}
call of mptt in some way to take a join string, but that would involve much more work.