基于Flask实现点击链接动态生成单食谱HTML页面的方法
实现Flask动态单食谱页面方案
1. 修改recipes.html的链接,传递食谱唯一标识
把原来固定的链接改成带食谱唯一ID的动态路由(优先用数据库自增ID,比标题更可靠,避免重复问题),修改表格中的a标签:
<table> <thead> <tr> <th>Recipe Title</th> <th>Total Time</th> <th>Difficulty</th> </tr> </thead> <tbody> {% for row in names %} <tr> <!-- 替换为带ID的动态路由 --> <td><a href="/recipe/{{row.id}}">{{row[0]}}</a></td> <td>{{row[1]}}</td> <td>{{row[2]}}</td> </tr> {% endfor %} </tbody> </table>
如果数据库里没有id字段,可临时用标题(需确保无重复)或循环索引,但强烈建议给食谱表添加自增ID字段。
2. 在Flask应用中添加动态路由
在主应用文件(如app.py)中新增接收食谱ID的路由,从数据库查询对应数据后传给模板。
原生SQL示例(以SQLite为例):
from flask import Flask, render_template import sqlite3 app = Flask(__name__) # 原有展示所有食谱的路由 @app.route('/recipes') def show_recipes(): conn = sqlite3.connect('your_database.db') cursor = conn.cursor() cursor.execute('SELECT id, title, total_time, difficulty FROM recipes') names = cursor.fetchall() conn.close() return render_template('recipes.html', names=names) # 新增单食谱路由 @app.route('/recipe/<int:recipe_id>') def show_single_recipe(recipe_id): conn = sqlite3.connect('your_database.db') cursor = conn.cursor() # 查询对应ID的完整食谱信息(按需调整字段) cursor.execute('SELECT * FROM recipes WHERE id = ?', (recipe_id,)) recipe = cursor.fetchone() conn.close() # 处理食谱不存在的情况 if not recipe: return render_template('404.html'), 404 return render_template('single_recipe.html', recipe=recipe) if __name__ == '__main__': app.run(debug=True)
SQLAlchemy ORM示例:
from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db' db = SQLAlchemy(app) # 定义食谱模型 class Recipe(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) total_time = db.Column(db.String(20)) difficulty = db.Column(db.String(20)) ingredients = db.Column(db.Text) instructions = db.Column(db.Text) @app.route('/recipes') def show_recipes(): recipes = Recipe.query.all() names = [(r.id, r.title, r.total_time, r.difficulty) for r in recipes] return render_template('recipes.html', names=names) @app.route('/recipe/<int:recipe_id>') def show_single_recipe(recipe_id): # 自动处理404 recipe = Recipe.query.get_or_404(recipe_id) return render_template('single_recipe.html', recipe=recipe)
3. 创建动态单食谱模板single_recipe.html
根据传入的recipe数据动态渲染内容,无需硬编码:
<!DOCTYPE html> <html> <head> <title>{{ recipe.title }}</title> </head> <body> <h1>{{ recipe.title }}</h1> <p><strong>总耗时:</strong> {{ recipe.total_time }}</p> <p><strong>难度:</strong> {{ recipe.difficulty }}</p> <h2>原料</h2> <!-- 如果原料是换行分隔的字符串,可拆分渲染为列表 --> <ul> {% for ing in recipe.ingredients.split('\n') %} <li>{{ ing }}</li> {% endfor %} </ul> <h2>制作步骤</h2> <ol> {% for step in recipe.instructions.split('\n') %} <li>{{ step }}</li> {% endfor %} </ol> <a href="/recipes">返回食谱列表</a> </body> </html>
可根据数据库实际字段调整模板中的变量和渲染方式。
关键说明
- 依赖数据库中食谱的唯一标识(如
id),确保路由能精准定位食谱; - 用户新增食谱后,列表页会自动同步,单食谱页面无需额外修改即可识别新数据;
- 加入404处理,避免用户访问不存在的食谱时出错。
内容的提问来源于stack exchange,提问作者Oscar5
相关产品推荐
相关产品推荐

