为每个目录创建python flask < div>

bpsygsoo  于 2023-01-03  发布在  Python
关注(0)|答案(1)|浏览(174)

如何使用flask为每个目录创建一个div?
我尝试了这个,但它没有做任何事情,也没有在控制台:
python文件:

# Get a list of directories in the 'servers' directory
    folders = [d for d in os.listdir('servers/') if os.path.isdir(d)]

    # Create a div element for each folder
    divs = []
    for folder in folders:
        div = f"<div class='list'><a href='/servers/{folder}'>{folder}</a></div>"
        divs.append(div)

    # Join the div elements into a single string
    divs_string = "\n".join(divs)

    # Render the template and pass the div elements as a variable
    return render_template('home.html')

html文件(home.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/home.css') }}" />
    <link rel="stylesheet" href="https://rawcdn.githack.com/CrystalVortex/Feather-CSS/9318334ceedfa61d6a64349a558ef1e48ef19cb2/Feather1.7.css">
    <title>FeatherPanel | Home</title>
</head>
<body>
    <form action="/create" method="post">
    <button class="btn_blue">Create Server</button>
    </form>
    {% for directory in directories %}
        <div>{{ directory }}</div>
    {% endfor %}

</body>
</html>
qxsslcnc

qxsslcnc1#

listdir函数只返回一个文件名列表。为了在循环中测试它是否是一个目录,isdir函数需要包含文件夹名的路径。
然后可以将返回的列表传递给模板。
我在这里使用locals()将所有的局部变量传递给模板,但是,你也可以用一个键单独传递变量。

@app.route('/servers/')
def servers():
    # Get a list of directories in the 'servers' directory
    folders = [d for d in os.listdir('servers') if os.path.isdir(os.path.join('servers', d))]

    # Render the template and pass the div elements as a variable
    return render_template('home.html', **locals())

在模板中,您可以迭代上述列表,为每个条目创建一个“div”元素。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/home.css') }}" />
    <link rel="stylesheet" href="https://rawcdn.githack.com/CrystalVortex/Feather-CSS/9318334ceedfa61d6a64349a558ef1e48ef19cb2/Feather1.7.css">
    <title>FeatherPanel | Home</title>
</head>
<body>
    <form action="/create" method="post">
        <button class="btn_blue">Create Server</button>
    </form>

    {% for folder in folders %}
        <div>{{ folder }}</div>
    {% endfor %}

</body>
</html>

您没有描述当用户单击列出目录的链接时应发生的情况。请记住,只有静态文件夹中的文件才能从客户端访问。如果要使用锚引用静态文件夹之外的列出目录,则需要另一个终结点。

相关问题