开发者

Django - create nested html list from list of dictionary objects

I have a Python list of dictionary in the form e.g.

[{'Parent':'top', 'Child':'obj1', 'Level':0},
 {'Parent':'obj1', 'Child':'obj2', 'Level':1},
 {'Parent':'obj1', 'Child':'obj3', 'Level':1},
 {'Parent':'obj2', 'Child':'obj4', 'Leve开发者_高级运维l':2},
 {'Parent':'obj4', 'Child':'obj5', 'Level':3}]

I want to write this out as a nested html list based on the Parent e.g.

  • obj1
    • obj2
      • obj4
        • obj5
    • obj3

How can I do this in a Django template


Quick solution:

def make_list(d):
    def append_children(parent, d):
        children = [[x['Child']] for x in d if x['Parent'] == parent[0]]
        if children:
            parent.append(children)
            for child in children:
                append_children(child, d)

    results = [[x['Child']] for x in d if x['Parent'] == 'top']
    for parent in results:
        append_children(parent, d)

    return results

Pass the list into this function and then apply unordered_list filter to the result. The disadvantage of this method is that <ul> list is created even for one element (<ul><li>elem</li></ul>), but you can alter display as you like with CSS.

If you want clearer HTML you should write a custom tag or filter for that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜