使用Flask渲染index.html模板遇TemplateNotFound错误求助
解决Jinja2 TemplateNotFound错误
问题出在两个核心错误上:
- 你设置的
template_folder参数值和实际模板目录名不匹配:实际目录是templates,但代码里写的是template - 调用
render_template时重复添加了目录前缀——template_folder已经指定了模板的根路径,调用时直接写文件名即可
修正后的代码
如果你的模板目录是templates(Flask默认约定,推荐使用),代码可以简化为:
from flask import Flask, render_template app = Flask(__name__) # 默认template_folder就是"templates",可省略该参数 @app.route("/") def home(): return render_template("index.html") # 直接传入模板文件名 if __name__ == "__main__": app.run(debug=True)
如果坚持使用template作为自定义目录名,修改为:
from flask import Flask, render_template app = Flask(__name__, template_folder="template") # 参数值匹配实际目录名 @app.route("/") def home(): return render_template("index.html") # 无需再添加目录前缀 if __name__ == "__main__": app.run(debug=True)
确认项目目录结构
确保你的文件层级符合以下其中一种:
情况1(默认推荐结构)
项目根目录/ ├── main.py(你的主代码文件) └── templates/ └── index.html
情况2(自定义目录结构)
项目根目录/ ├── main.py(你的主代码文件) └── template/ └── index.html
内容的提问来源于stack exchange,提问作者Nemiya
相关产品推荐
相关产品推荐

