【问题标题】:Is there a way to create an HTML table from a list using bottle有没有办法使用瓶子从列表中创建 HTML 表格
【发布时间】:2022-03-19 04:31:12
【问题描述】:

我正在使用 os.listdir 获取子目录列表,并希望将它们显示为网页上的表格。我正在为 web 框架使用瓶子。我在瓶子文档中看到,可以通过从列表中创建一个 sqlite 数据库并从那里加载它来完成,但理想情况下我正在寻找一种避免该中间步骤的方法。如果没有 sqlite 步骤,我找不到任何文档,想知道是否可能?

下面的当前代码在网页上显示我想要的信息,但显示为单行文本。

当前代码:
瓶子应用

from bottle import Bottle, template, route, run, static_file
import os
import sys

app = Bottle()

dirname = os.path.dirname(sys.argv[0])

@app.route('/static/<filename:re:.*\.css>')
def send_css(filename):
    return static_file(filename, root=dirname+'/static/')


@app.route('/')
def index():
    dir_loc = "/Users/me/Documents"
    dir_data = list(os.listdir(dir_loc))

    return template('index', data = dir_data)


run(app, host='localhost', port=8080, debug=True)

index.tpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="static/styling.css">
</head>
<body>
    <div>
        <p>Template for bottle showing {{data}}</p>
    </div>
</body>
</html>

【问题讨论】:

  • 您不需要(或不想要)一个数据库。查看模板中的循环 - for 循环似乎合适。

标签: python bottle


【解决方案1】:

不需要 SQL 数据库(除非您希望它用于持久性)。您可以生成带有循环的表格和列表,在 Bottle doc PDF 中有很好的描述。

这是一个简单的例子:

server.py

from bottle import route, run, template
import os

@route("/")
def index():
    dir_loc = "/Users/me/Documents" # replace "me" with your username
    dir_data = list(os.listdir(dir_loc))
    return template("index.tpl", data=dir_data)

if __name__ == "__main__":
    run(host="localhost", port=8080, debug=True, reloader=True)

index.tpl

<!DOCTYPE html>
<html>
<body>
  <table>
    <tbody>
    % for file in data:
      <tr>
        <td>{{file}}</td>
      </tr>
    % end
    </tbody>
  </table>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    相关资源
    最近更新 更多