简体   繁体   中英

Django - create nested html list from list of dictionary objects

I have a Python list of dictionary in the form eg

[{'Parent':'top', 'Child':'obj1', 'Level':0},
 {'Parent':'obj1', 'Child':'obj2', 'Level':1},
 {'Parent':'obj1', 'Child':'obj3', 'Level':1},
 {'Parent':'obj2', 'Child':'obj4', 'Level':2},
 {'Parent':'obj4', 'Child':'obj5', 'Level':3}]

I want to write this out as a nested html list based on the Parent eg

  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM