我正在构建一个定制的动态模板工具,它可以集成到任何模板框架中,比如pugs,jinja等等。我想让这个演示看起来像:
view! {
div {
p {
span {}
strong {}
}
}
}因此,从由Html标记组成的自定义json数据中,我希望生成已发布的输出,但在递归方面,除了顶部父标记之外,内部子标记没有打印出来,这是一个小问题。
tree_data = {
"tag": "html",
"children": [
{
"tag": "head",
"children": [
{
"tag": "meta",
"children": []
},
{
"tag": "title",
"children": []
}
]
},
{
"tag": "body",
"children": [
{
"tag": "ul0",
"children": [
{
"tag": "div0",
"children": []
},
{
"tag": "div1",
"children": []
},
{
"tag": "div2",
"children": []
}
]
},
{
"tag": "div3",
"children": [
{
"tag": "ul1",
"children": [
{
"tag": "li0",
"children": []
},
{
"tag": "li1",
"children": []
},
{
"tag": "li2",
"children": []
}
]
},
{
"tag": "div4",
"children": [
{
"tag": "h1-0",
"children": []
}
]
},
{
"tag": "div-5",
"children": [
{
"tag": "h2-0",
"children": []
}
]
}
]
},
{
"tag": "div6",
"children": [
{
"tag": "div7",
"children": [
{
"tag": "h1-1",
"children": []
},
{
"tag": "h1-2",
"children": []
},
{
"tag": "h2-3",
"children": []
}
]
}
]
},
{
"tag": "div-8",
"children": []
}
]
}
]
}用于生成标记的函数是:
def template_tags(d, c_tag=""):
d_tag = d['tag']
tag_tree = f'{c_tag} {{ {d_tag} }}'
for c in d['children']:
if c is not None:
c_tag = c['tag']
template_tags(c)
return(tag_tree)
my_view = f"""
view! {{
{template_tags(tree_data)}
}}
"""
print(my_view)这就是我得到的结果。如何对此代码进行调整以使整个树返回?
view! {
html
}发布于 2021-12-30 05:06:50
在函数中,需要收集递归调用生成的所有子节点。您还想在返回它们之前将其缩进。这意味着它需要返回一个列表,稍后您将合并该列表:
tree_data = {
"tag": "html",
"children": [
{
"tag": "head",
"children": [
{
"tag": "meta",
"children": []
},
{
"tag": "title",
"children": []
}
]
},
{
"tag": "body",
"children": [
{
"tag": "ul0",
"children": [
{
"tag": "div0",
"children": []
},
{
"tag": "div1",
"children": []
},
{
"tag": "div2",
"children": []
}
]
},
{
"tag": "div3",
"children": [
{
"tag": "ul1",
"children": [
{
"tag": "li0",
"children": []
},
{
"tag": "li1",
"children": []
},
{
"tag": "li2",
"children": []
}
]
},
{
"tag": "div4",
"children": [
{
"tag": "h1-0",
"children": []
}
]
},
{
"tag": "div-5",
"children": [
{
"tag": "h2-0",
"children": []
}
]
}
]
},
{
"tag": "div6",
"children": [
{
"tag": "div7",
"children": [
{
"tag": "h1-1",
"children": []
},
{
"tag": "h1-2",
"children": []
},
{
"tag": "h2-3",
"children": []
}
]
}
]
},
{
"tag": "div-8",
"children": []
}
]
}
]
}
def template_tags(d, c_tag=""):
d_tag = d['tag']
tag_tree = f'{c_tag} > {d_tag}'
myset = [tag_tree]
for c in d['children']:
if c:
c_tag = c['tag']
res = template_tags(c)
myset.extend([' '+s for s in res])
return myset
nl = '\n'
my_view = f"""
view! {{
{nl.join(template_tags(tree_data))}
}}
"""
print(my_view)输出:
view! {
> html
> head
> meta
> title
> body
> ul0
> div0
> div1
> div2
> div3
> ul1
> li0
> li1
> li2
> div4
> h1-0
> div-5
> h2-0
> div6
> div7
> h1-1
> h1-2
> h2-3
> div-8
} https://stackoverflow.com/questions/70527545
复制相似问题