如何从django-mptt创建一个json树? [英] How can create a json tree from django-mptt?

查看:836
本文介绍了如何从django-mptt创建一个json树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript InfoVis Tooljit( http://thejit.org )来呈现一个mptt节点树在django。如何创建所需的json结构(请参阅 http:// thejit .org / static / v20 / Jit / Examples / Spacetree / example1.code.html 在django?

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?

谢谢

推荐答案

如果您使用django-mptt的模板功能生成JSON数据,则应该可以执行以下操作:

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 %}

孩子标签是辉煌的,基本上调用recursetree为每个孩子的节点。然而,这个解决方案的逗号之间有一点点的混乱,因为mptt的例子就是这些事情不是问题的列表元素。

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 %}]
}

区分根节点(假设只有一个)不驻留在数组中,而是分配给一个变量,与其他生存在另一个节点的子节点的节点相比较, var x = y,问题避免。

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.

children还有一个问题:[x,y,z ,有一个逗号。如果最后一个逗号引起错误,那么在调用该模板的视图中,您可以随时使用一个快速的字符串替换来将,] 替换为]

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 ]

或者,您可以以某种方式更改mptt的 {{children}} 拿一个连接字符串,但这将涉及更多的工作。

Alternatively you could alter the {{ children }} call of mptt in some way to take a join string, but that would involve much more work.

这篇关于如何从django-mptt创建一个json树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆