Python Flask — 使用后端数据创建 HTML 表格

在本文中,我们将讨论如何将一些表格数据从后端传递到 HTML 前端,并基于这些数据创建一个外观不错的表格。

我们的文件结构

为了简单起见,让我们只处理 2 个文件:

  • templates/index.html(在 templates 文件夹内)
  • app.py

app.py 中的代码

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():

    headers = ['fruit', 'price', 'country']

    tableData = [
        {'fruit':'apple', 'price':4, 'country':'singapore'},
        {'fruit':'orange', 'price':5, 'country':'singapore'},
        {'fruit':'pear', 'price':6, 'country':'singapore'},
        {'fruit':'apple', 'price':7, 'country':'malaysia'},
        {'fruit':'orange', 'price':8, 'country':'malaysia'},
        {'fruit':'pear', 'price':9, 'country':'malaysia'},
    ]

    return render_template(
        'index.html',
        headers=headers,
        tableData=tableData
    )

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

app.py 包含我们的 Python Flask 应用程序。 请注意,表格标题和表格数据本身在 render_template 函数中传递给我们的 HTML 模板 index.html。

我们希望以表格格式在我们的 HTML 前端中显示此数据。

templates/index.html 中的代码

此 HTML 文件从我们的 Python Flask 后端接收数据。 更具体地说,它接收 2 个变量——headers 和 tableData。

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

<div class="px-5 mx-5">
    <h1>My Table</h1>

    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                {% for header in headers %}
                    <th>{{header}}</th>
                {% endfor %}
            </tr>
        </thead>

        <tbody>
            {% for row in tableData %}
                <tr>
                    <td>{{row['fruit']}}</td>
                    <td>{{row['price']}}</td>
                    <td>{{row['country']}}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    
</div>

当我们运行我们的应用程序时会发生什么

我们得到这个网页。

最后

希望本文对您有所帮助!