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

如何通过Flask的render_template传递JSON数组至HTML页面展示考勤状态

解决Flask传递考勤数组并在看板展示的问题

后端Flask代码:直接传递整个数组

你不需要单独提取单个元素,直接把API返回的完整数组作为参数传给render_template即可。示例代码如下:

from flask import Flask, render_template
import requests

app = Flask(__name__)

@app.route('/attendance-board')
def show_attendance():
    # 调用考勤API获取数据(替换为你的实际API地址)
    attendance_data = requests.get("你的考勤API接口URL").json()
    # 将完整数组传递给HTML模板
    return render_template('attendance_board.html', students=attendance_data)

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

前端HTML模板:循环渲染数组内容

在HTML中使用Jinja2的for循环遍历整个数组,逐个渲染每位学生的考勤状态,同时通过CSS实现看板样式:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>考勤监控看板</title>
    <style>
        .board-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 18px;
            padding: 25px;
        }
        .student-card {
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 3px 6px rgba(0,0,0,0.1);
            font-family: Arial, sans-serif;
        }
        .present {
            background-color: #e6f9e6;
            border-left: 6px solid #2ecc71;
        }
        .absent {
            background-color: #ffebee;
            border-left: 6px solid #e74c3c;
        }
        h2 {
            text-align: center;
            color: #333;
        }
    </style>
</head>
<body>
    <h2>学生考勤状态看板</h2>
    <div class="board-container">
        <!-- 遍历students数组,渲染每个学生信息 -->
        {% for student in students %}
            <div class="student-card {{ student.Status.lower() }}">
                <h3>{{ student.StudentName }}</h3>
                <p>考勤状态:<strong>{{ student.Status }}</strong></p>
            </div>
        {% endfor %}
    </div>
</body>
</html>

核心说明

  1. 后端直接传递API返回的完整数组,无需拆分单个元素
  2. 前端通过{% for student in students %}循环遍历数组,每个student对象可直接访问StudentName和Status属性
  3. 利用CSS Grid实现响应式看板布局,通过状态类名区分出勤/缺勤的视觉样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:30:47