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

如何在HTML表格中渲染字典数组形式的预约数据?

解决Flask中预约数据的表格渲染问题

问题描述

我是Python(Flask)及编程领域的新手。需要将存储预约信息的字典数组数据渲染到HTML表格中,每个预约字典包含'day'、'time'、'courttype'、'name'、'phone'这些键。需校验每个预约的'day'、'hour'和'courttype',将对应的'name'显示在表格的对应行列位置。

现有代码如下:

UT2_Tasca.py

from flask import Flask, render_template, request
app = Flask(__name__)

# Array of reservations
reservas = []

# Function to create reservation (dict) and store in array
def crearReserva(reqdia, reqhora, reqtipopista, reqnom, reqtelefon):

    reserva = { 'dia': reqdia, 'hora': reqhora, 'tipopista': reqtipopista, 'nom': reqnom,   'telefon': reqtelefon}
 
    reservas.append(reserva)


@app.route('/')
def index():
    global reservas
    return render_template('UT2_exemple4_registre.html')

@app.route('/formulari', methods=['GET', 'POST'])
def formulari():
    return render_template('UT2_exemple4_registre.html')

@app.route('/reserves', methods=['GET','POST'])
def reserves():

    global reservas
    # array of title (weekday and hours) that will appear in the table headings
    titleColumn = ['','Monday','Tuesday','Wednesday','Thursday','Friday']
    titleRow = ['15:00','16:00','17:00','18:00','19:00','20:00']

    if request.method == 'POST':

        # get data from form (request)
        reqdia = request.form['dia']
        reqhora = request.form['hora']
        reqtipopista = request.form['tipopista']
        reqnom = request.form['nom']
        reqtelefon = request.form['telefon']
        
        crearReserva (reqdia, reqhora, reqtipopista, reqnom, reqtelefon)

    else:
        return render_template('UT2_exemple4_reserves.html', reservas=reservas, row=titleRow, col=titleColumn)

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

UT2exemple4_reserves.html

...
<div>
        <table>
          <thead>
            {% for c in col %} <!-- prints columns heading of table -->
            <th>{{c}}</th>
            {% endfor %}
          </thead>
          <tbody>
            {% for f in row %} <!-- prints rows heading of table -->
              <tr>
                <th>{{f}}</th>
                {% for res in reservas %}  
                <td> HERE I'D LIKE TO PRINT THE NAME OF THE PERSON THAT HAS MADE THE RESERVATION. BUT FIRST, SOMEHOW, I NEED TO CHECK/READ THE DAY, HOUR AND COURTTYPE AND THEN PRINT THE NAME... NOT SURE IF THAT IS POSIBLE ON HTML...</td>
                {% endfor %}
              </tr>
            {% endfor %}
          </tbody>
        </table>
</div>
...

我的思路是通过{% for res in reservas %}获取单个预约数据,然后校验其day、hour和courttype,将name显示在表格对应位置,但不确定如何在HTML中实现,请问是否有可行的方法?


解决方案

直接在HTML循环所有预约匹配会重复生成单元格,更高效的方式是在后端先将预约数据转换成便于表格查询的结构,再传递给前端渲染。

步骤1:调整后端代码,重构预约数据结构

修改/reserves路由,把预约数据转换成嵌套字典,用(日期, 时间, 场地类型)作为唯一键,对应值为预约人姓名,方便前端快速查询:

@app.route('/reserves', methods=['GET','POST'])
def reserves():
    global reservas
    titleColumn = ['','Monday','Tuesday','Wednesday','Thursday','Friday']
    titleRow = ['15:00','16:00','17:00','18:00','19:00','20:00']

    if request.method == 'POST':
        reqdia = request.form['dia']
        reqhora = request.form['hora']
        reqtipopista = request.form['tipopista']
        reqnom = request.form['nom']
        reqtelefon = request.form['telefon']
        crearReserva(reqdia, reqhora, reqtipopista, reqnom, reqtelefon)
    
    # 转换为可快速查询的映射结构
    reserva_map = {}
    for res in reservas:
        key = (res['dia'], res['hora'], res['tipopista'])
        reserva_map[key] = res['nom']
    
    # 修复POST后无响应问题,统一返回模板
    return render_template('UT2_exemple4_reserves.html', 
                           reserva_map=reserva_map, 
                           row=titleRow, 
                           col=titleColumn)

步骤2:修改HTML模板,匹配对应位置的预约信息

前端遍历表格的行(时间)和列(日期),通过reserva_map查询对应位置的预约姓名。以下是单一场地类型的渲染示例,若需支持多场地类型,可在外层增加场地类型循环:

...
<div>
    <h3>硬地场地预约表</h3>
    <table border="1">
        <thead>
            {% for c in col %}
            <th>{{c}}</th>
            {% endfor %}
        </thead>
        <tbody>
            {% for hour in row %}
            <tr>
                <th>{{hour}}</th>
                {% for day in col[1:] %} <!-- 跳过第一个空列标题 -->
                <td>
                    <!-- 查询当前日期、时间、场地类型对应的预约人 -->
                    {{ reserva_map.get((day, hour, "硬地"), "") }}
                </td>
                {% endfor %}
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
...

补充说明

  • 三元组键(日期, 时间, 场地类型)确保每个预约组合唯一,避免数据覆盖;
  • 修复了原代码中POST请求后无返回的问题,提交预约后可直接看到更新后的表格;
  • 若需多场地类型,可在后端传递场地类型列表,前端循环生成对应表格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:25:25