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

Flask中如何传递数据库信息到HTML模板并实现菜谱点击查询详情

解决点击菜谱获取详情的问题

核心思路

通过在跳转链接中携带菜谱的唯一标识(ID最优,名称易重复/含特殊字符),让详情页路由接收该标识后查询数据库,返回对应菜谱的详情内容。


1. 新增详情页路由

在views蓝图中添加接收菜谱ID的路由,用于查询并返回详情:

@views.route('/recipe/<int:recipe_id>')
def recipe_detail(recipe_id):
    # 通过ID查询菜谱,找不到则返回404页面
    recipe = recipeMaster.query.get_or_404(recipe_id)
    # 将菜谱数据传入详情模板
    return render_template("recipe_detail.html", recipe=recipe)

2. 修改首页链接模板

更新<a>标签的href,通过url_for传递菜谱ID参数:

{% for row in rows %}
<div class="card">
    <div class="card-body">
        <!-- 动态生成带菜谱ID的跳转链接 -->
        <a href="{{ url_for('views.recipe_detail', recipe_id=row.id) }}">
            {{ row.recipe_name }}
        </a>
    </div>
</div>
<br>
{% endfor %}

注:原代码中的<tr>/<td>是表格标签,放在卡片容器里不符合HTML结构规范,直接显示菜谱名称即可。

3. 编写详情页模板(recipe_detail.html)

接收路由传递的recipe对象,填充详情内容:

<div class="card">
    <div class="card-body">
        <h2>{{ recipe.recipe_name }}</h2>
        <p>食材:{{ recipe.ingredients }}</p>
        <p>步骤:{{ recipe.steps }}</p>
        <!-- 根据你的数据库字段,添加更多详情内容 -->
    </div>
</div>

备选方案:用菜谱名称作为参数(不推荐)

如果必须用名称传递,需注意名称的唯一性和URL编码问题:

路由修改:

@views.route('/recipe/<string:recipe_name>')
def recipe_detail_by_name(recipe_name):
    recipe = recipeMaster.query.filter_by(recipe_name=recipe_name).first_or_404()
    return render_template("recipe_detail.html", recipe=recipe)

模板链接修改:

<a href="{{ url_for('views.recipe_detail_by_name', recipe_name=row.recipe_name) }}">
    {{ row.recipe_name }}
</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:09:25