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

在Flask的HTML模板中用Python并行遍历多个列表的实现问题

嘿,我来帮你搞定这个在Flask模板里并行遍历多个列表的问题!

核心思路是在Python端把两个有对应关系的列表打包成配对的元组,再传到模板里,最后用Jinja2的循环语法遍历这个打包后的对象即可。

第一步:修改Flask路由代码

我先帮你补全并调整index函数的逻辑,重点是用zip()把productnames和reviews打包后传给模板:

from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)
app.config["DEBUG"] = True

productnames = []
reviews = []

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        # 处理表单提交,获取产品名和评论内容
        product_name = request.form.get("productname")
        review_text = request.form.get("review")
        # 确保内容不为空再添加到列表
        if product_name and review_text:
            productnames.append(product_name)
            reviews.append(review_text)
        # 重定向回首页,避免表单重复提交
        return redirect(url_for("index"))
    
    # GET请求时,把两个列表打包成配对的元组集合
    combined_items = zip(productnames, reviews)
    # 将打包后的对象传给模板
    return render_template("index.html", combined=combined_items)

第二步:修改HTML模板

在你的index.html中,通过Jinja2循环遍历combined,取出对应的产品名和评论填充到表格里:

<!DOCTYPE html>
<html>
<head>
    <title>产品评论列表</title>
</head>
<body>
    <!-- 可选:添加提交评论的表单,方便测试功能 -->
    <form method="POST">
        <label>产品名称:</label>
        <input type="text" name="productname" required>
        <br>
        <label>评论内容:</label>
        <textarea name="review" rows="3" required></textarea>
        <br>
        <button type="submit">提交评论</button>
    </form>

    <!-- 展示评论的表格 -->
    <h3>已提交的产品评论</h3>
    <table border="1" cellpadding="8">
        <thead>
            <tr>
                <th>产品名称</th>
                <th>评论内容</th>
            </tr>
        </thead>
        <tbody>
            {% for product, review in combined %}
            <tr>
                <td>{{ product }}</td>
                <td>{{ review }}</td>
            </tr>
            {% else %}
            <!-- 没有评论时显示提示 -->
            <tr>
                <td colspan="2" style="text-align:center;">暂无评论,快来添加第一条吧!</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

小提醒

  • zip()会把两个列表对应位置的元素配对,如果两个列表长度不一致,zip()会以较短的列表为准,超出的元素会被忽略。如果需要处理长度不匹配的场景,可以用itertools.zip_longest(需要先导入itertools模块),它会用默认值填充较短的列表。
  • POST请求后用redirect(url_for("index"))重定向,是为了避免用户刷新页面时重复提交表单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:29:22