如何在Flask中将MySQL查询结果赋值到HTML文档?
解决方案
1. 优化SQL查询,关联分类与数量
原查询仅返回数量总和,无法对应到具体分类,需修改SQL同时获取分类名称:
cur.execute("SELECT category, sum(quantity) AS total_quantity FROM pydb.products GROUP BY category")
2. 在Flask视图中处理数据并传递到模板
将查询结果转为字典,方便模板按分类名称调用对应数量:
# 转为字典,键为分类名称,值为对应数量 category_totals = {row[0]: row[1] for row in cur.fetchall()} # 传递到目标模板(假设模板名为product_stats.html) return render_template('product_stats.html', category_totals=category_totals)
3. 在HTML模板中填充数量数据
利用Jinja2模板语法,将对应分类的数量插入到.quantity标签中:
<ul id="autoWidth" class="cs-hidden"> <li class="item-a"> <div class="box"> <div class="slide-img"> <img src="static/images/1.webp" alt="1" /> <div class="overlay"> <a href="/details/camera" class="details-btn">View Details</a> </div> </div> <div class="detail-box"> <div class="type"> <a href="#">Camera & Camcorders</a> <span> </span> </div> <a href="#" class="quantity">{{ category_totals.get('Camera & Camcorders', 0) }}</a> </div> </div> </li> <li class="item-b"> <div class="box"> <div class="slide-img"> <img src="static/images/2.jfif" alt="2" /> <div class="overlay"> <a href="/details/laptop" class="details-btn">View Details</a> </div> </div> <div class="detail-box"> <div class="type"> <a href="#">Laptops</a> <span> </span> </div> <a href="#" class="quantity">{{ category_totals.get('Laptops', 0) }}</a> </div> </div> </li> </ul>
- 使用
get()方法可避免分类不存在时抛出异常,默认返回0
进阶:动态渲染所有分类(推荐)
如果后续会新增分类,硬编码HTML会很繁琐,可直接循环渲染所有分类项:
Flask视图修改:
# 获取分类与数量的列表 cur.execute("SELECT category, sum(quantity) AS total_quantity FROM pydb.products GROUP BY category") category_list = cur.fetchall() return render_template('product_stats.html', category_list=category_list)
HTML模板修改:
<ul id="autoWidth" class="cs-hidden"> {% for category, total in category_list %} <li class="item-{{ category.lower().replace(' ', '-') }}"> <div class="box"> <div class="slide-img"> <!-- 根据分类索引匹配图片,可根据实际情况调整图片命名规则 --> <img src="static/images/{{ loop.index }}.{% if loop.index ==1 %}webp{% else %}jfif{% endif %}" alt="{{ category }}" /> <div class="overlay"> <!-- 生成详情页链接,根据实际路由规则调整 --> <a href="/details/{{ category.lower().replace(' & ', '-').replace(' ', '-') }}" class="details-btn">View Details</a> </div> </div> <div class="detail-box"> <div class="type"> <a href="#">{{ category }}</a> <span> </span> </div> <a href="#" class="quantity">{{ total }}</a> </div> </div> </li> {% endfor %} </ul>
内容的提问来源于stack exchange,提问作者luciferRayan
相关产品推荐
相关产品推荐

