You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask的Jinja2 HTML中展示树形结构?

网页端展示树形ASCII结构的解决方案

下面提供两种可行的实现方案,分别基于后端(Flask+Jinja2)和前端JavaScript实现,满足你动态展示树形结构的需求。


方案一:后端生成ASCII树(Flask + Jinja2)

利用你熟悉的treelib在后端生成ASCII树形字符串,再通过Flask传给Jinja2模板展示,适合数据量较大或希望逻辑集中在后端的场景。

1. Flask后端代码

from flask import Flask, render_template
from treelib import Tree

app = Flask(__name__)

def build_ascii_tree(tree_dict, root_node):
    # 用treelib构建树
    tree = Tree()
    tree.create_node(root_node, root_node)
    
    # 递归添加子节点
    def add_child_nodes(parent):
        if parent in tree_dict:
            for child in tree_dict[parent]:
                tree.create_node(child, child, parent=parent)
                add_child_nodes(child)
    
    add_child_nodes(root_node)
    
    # 生成ASCII格式的树形字符串
    output_buffer = []
    tree.show(stdout=False, line_type='ascii', output=output_buffer)
    return '\n'.join(output_buffer)

@app.route('/')
def show_tree():
    # 这里可以替换为用户动态输入的数据
    user_tree_dict = {'A':['B', 'C'], 'B':['D','E'], 'C':['F', 'G', 'H'], 'E':['I', 'J']}
    root = 'A'
    ascii_tree = build_ascii_tree(user_tree_dict, root)
    return render_template('tree_view.html', tree_content=ascii_tree)

if __name__ == '__main__':
    app.run(debug=True)

2. Jinja2模板(templates/tree_view.html)

用<pre>标签保留ASCII格式的空格和换行,同时添加基础样式优化展示:

<!DOCTYPE html>
<html>
<head>
    <title>树形结构展示</title>
    <style>
        pre {
            font-family: monospace;
            background-color: #f5f5f5;
            padding: 16px;
            border-radius: 6px;
            max-width: 800px;
            margin: 20px auto;
        }
        h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>树形结构</h1>
    <pre>{{ tree_content }}</pre>
</body>
</html>

方案二:前端JavaScript生成ASCII树

后端仅传递原始树形字典和根节点,由前端JS递归生成ASCII结构,适合需要动态交互或前端自主处理数据的场景。

1. Flask后端代码

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def show_tree():
    # 用户动态数据
    user_tree_dict = {'A':['B', 'C'], 'B':['D','E'], 'C':['F', 'G', 'H'], 'E':['I', 'J']}
    root = 'A'
    return render_template('tree_js_view.html', tree_data=user_tree_dict, root_node=root)

if __name__ == '__main__':
    app.run(debug=True)

2. 前端模板(templates/tree_js_view.html)

通过JS递归遍历字典,拼接出符合要求的ASCII树形字符串:

<!DOCTYPE html>
<html>
<head>
    <title>JS生成树形结构</title>
    <style>
        pre {
            font-family: monospace;
            background-color: #f5f5f5;
            padding: 16px;
            border-radius: 6px;
            max-width: 800px;
            margin: 20px auto;
        }
        h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>树形结构</h1>
    <pre id="tree-container"></pre>

    <script>
        function generateAsciiTree(treeData, root) {
            const lines = [root];
            
            // 递归生成每一行内容
            function traverse(node, prefix, isLastChild) {
                // 添加当前节点的行
                lines.push(`${prefix}${isLastChild ? '└── ' : '├── '}${node}`);
                const children = treeData[node] || [];
                
                // 处理子节点的前缀
                for (let i = 0; i < children.length; i++) {
                    const childIsLast = i === children.length - 1;
                    const newPrefix = prefix + (isLastChild ? '    ' : '│   ');
                    traverse(children[i], newPrefix, childIsLast);
                }
            }
            
            // 处理根节点的子节点
            const rootChildren = treeData[root] || [];
            rootChildren.forEach((child, index) => {
                const isLast = index === rootChildren.length - 1;
                traverse(child, '', isLast);
            });
            
            return lines.join('\n');
        }

        // 从后端获取数据并生成树形结构
        const treeData = {{ tree_data|tojson }};
        const root = "{{ root_node }}";
        document.getElementById('tree-container').textContent = generateAsciiTree(treeData, root);
    </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Shane S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 11:50:31