Python递归生成自定义标签问题:修复仅输出顶层父标签的递归逻辑以实现完整嵌套模板结构
修复动态模板标签的递归渲染问题
我来帮你解决这个递归逻辑的问题!你的代码核心问题是递归调用时没有收集子节点的输出结果,也没有将它们整合到当前标签的结构中,导致最终只返回了顶层的html标签,内部子标签完全没被渲染。
修复后的完整代码
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): # 获取当前节点的标签名 current_tag = d['tag'] # 获取当前节点的子节点列表 children = d['children'] # 如果没有子节点,直接返回空标签结构 if not children: return f'{current_tag} {{ }}' # 递归生成每个子节点的标签结构,并拼接成字符串 child_content = ' '.join(template_tags(child) for child in children) # 返回当前标签包裹子节点的完整结构 return f'{current_tag} {{ {child_content} }}' my_view = f"""view! {{ {template_tags(tree_data)} }} """ print(my_view)
关键修改说明
- 移除冗余参数:删掉了原函数中的
c_tag参数,因为递归只需要处理当前节点及其子节点,不需要父标签传递额外信息。 - 处理空子节点:当节点没有子标签时,直接返回
tag {}的空结构,完全符合你期望的格式。 - 收集递归结果:用
join方法把所有子节点递归生成的标签结构拼接起来,嵌入到当前标签的大括号内部,实现层级嵌套效果。 - 返回完整结构:每个递归调用都会返回当前节点及其所有子节点的完整标签树,而不是只返回当前节点的孤立结构。
运行结果
执行上述代码后,你会得到完整的嵌套标签结构:
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 {} } } }
内容的提问来源于stack exchange,提问作者alexander
相关产品推荐
相关产品推荐

