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

Flask项目中HTML页面无法展示多字典结果问题求助(附完整代码)

问题解决:Flask展示所有字典结果

问题根源

你的后端代码在for item in data循环中,第一次迭代就执行了return render_template(...),直接终止循环并返回第一个商品的数据,导致页面仅能显示单个结果。

后端代码修改

将所有商品数据整理为列表,一次性传递给模板:

@app.route('/results')
def results():
    parameters = {
        "product_type": "blush"
    }
    # 注意:requests的GET方法为小写get,原代码的Get会触发错误
    response = requests.get(API, json=parameters)
    response.raise_for_status()
    data = response.json()
    # 直接将完整的商品数据列表传给模板
    return render_template('results.html', products=data)

前端HTML修改

使用Jinja2的for循环遍历商品列表,逐个渲染每个商品的信息:

{% include 'header.html' %}

<body>
    <section id="results">
            <h1 class="results-heading">Search Results</h1>
            <hr>
            <!-- 遍历所有商品数据 -->
            {% for item in products %}
            <div class="contents">
                <p class="content-title"><strong>Brand: </strong>{{ item.brand }}</p>
                <p class="content-title"><strong>Name: </strong>{{ item.name }}</p>
                <p class="content-title"><strong>Product Price: </strong>
                    {% if item.price %}
                    ${{ item.price.split('.')[0] }}
                    {% else %}
                        Not available
                    {% endif %}
                </p>
                <p class="content-title"><strong>Product Description: </strong>{{ item.description }}</p>
                <p class="content-title"><strong>Product Link: </strong><a href="{{ item.product_link }}">{{ item.product_link }}</a></p>
                <p class="content-title"><strong>Website Link: </strong><a href="{{ item.website_link }}">{{ item.website_link }}</a></p>
                <p class="content-title"><strong>Relevant Tags: </strong>
                    {% if item.tag_list %}
                        {% for tag in item.tag_list %}
                            {{ tag }}{% if not loop.last %}, {% endif %}
                        {% endfor %}
                    {% else %}
                        No Tags
                    {% endif %}
                </p>
                <!-- 商品间添加分隔线,提升可读性 -->
                {% if not loop.last %}
                <hr>
                {% endif %}
            </div>
            {% endfor %}
    </section>
</body>

额外优化:标签遍历中添加{% if not loop.last %}, {% endif %},避免最后一个标签后多余逗号;商品间增加分隔线,优化页面布局。

内容的提问来源于stack exchange,提问作者Emmanuella Ndukwe-Obiukwu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:05:30