首页  >  问答  >  正文

Html创建不同长度的表(在flask中首选)

<p>我想从数据库中获取数据,并将其导入到网站表中。假设sql数据库中有50行。那么表中一定有50行。但是,当我尝试创建一个表,我必须通过手动添加每个行和颜色的标签。那么我应该添加几十个声音行,并通过控制它们的可见性来实现这一点吗?我目前使用烧瓶,但如果没有办法实现它的烧瓶,其他方式也被接受。</p>
P粉133321839P粉133321839445 天前513

全部回复(1)我来回复

  • P粉401901266

    P粉4019012662023-08-02 12:32:15

    在Flask中,您可以根据SQL数据库中的数据动态生成具有不同长度的HTML表。您不需要手动创建数千行并控制其可见性。相反,您可以使用集成到Flask中的模板引擎来轻松实现这一点。希望这对你有帮助

    从SQL数据库中检索数据:使用Flask的数据库集成从数据库中获取数据。

    将数据传递给模板:在您的Flask路由中,将从数据库检索到的数据作为变量传递给HTML模板。

    使用模板:在HTML模板中,使用语法遍历数据并动态生成表行和单元格。


    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    # Replace this with your database connection and query code to fetch data
    # For demonstration purposes, let's assume you have fetched data in the 'rows' variable
    rows = [
        {'id': 1, 'name': 'John', 'age': 25},
        {'id': 2, 'name': 'Jane', 'age': 30},
        # Add more rows as needed
    ]
    
    @app.route('/')
    def index():
        return render_template('table_template.html', rows=rows)
    
    if __name__ == '__main__':
        app.run(debug=True)

    HTML FILE

    <!DOCTYPE html>
    <html>
    <head>
        <title>Dynamic Table</title>
        <style>
            /* Add border to the table */
            table {
                border-collapse: collapse;
                width: 100%;
                border: 1px solid black;
            }
    
            /* Add bold font style to the header row */
            th {
                font-weight: bold;
            }
    
            /* Add border to table cells (optional) */
            td, th {
                border: 1px solid black;
                padding: 8px;
            }
        </style>
    </head>
    <body>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                {% for row in rows %}
                    <tr>
                        <td>{{ row.id }}</td>
                        <td>{{ row.name }}</td>
                        <td>{{ row.age }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </body>
    </html>

    回复
    0
  • 取消回复