
Flask 的 render_template() 函数默认从项目根目录下的 templates/ 文件夹中查找模板,因此传入路径时不应包含 templates/ 前缀,直接使用 "home.html" 即可,否则会因路径错误导致 TemplateNotFound 异常。
flask 的 `render_template()` 函数默认从项目根目录下的 `templates/` 文件夹中查找模板,因此传入路径时不应包含 templates/ 前缀,直接使用 "home.html" 即可,否则会因路径错误导致 templatenotfound 异常。
在 Flask 中,render_template() 的设计遵循约定优于配置(Convention over Configuration)原则:它自动将模板路径解析为相对于 templates/ 目录的相对路径,而非文件系统绝对路径。这意味着你只需提供模板文件名(或子目录下的相对路径),Flask 会自动在 templates/ 文件夹内定位。
✅ 正确写法(假设 home.html 位于 templates/home.html):
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template("home.html") # ✅ 正确:不带 templates/
❌ 错误写法(引发 TemplateNotFound):
return render_template("templates/home.html") # ❌ 错误:Flask 会尝试查找 templates/templates/home.html
? 验证项目结构是否合规:
确保你的项目目录结构如下(templates/ 必须是 Flask 应用实例所在目录的同级子目录):
your_project/ ├── app.py # 或 main.py,Flask 入口文件 ├── templates/ # ← 必须存在且命名准确(全小写,无空格) │ └── home.html └── static/ # (可选)存放 CSS/JS 等静态资源
⚠️ 注意事项:
- templates 文件夹名称必须为全小写 templates(Flask 严格区分大小写);
- 不要手动创建嵌套的 templates/templates/;
- 若需组织子目录,如 templates/pages/about.html,则调用时写 render_template("pages/about.html");
- 使用 PyCharm 时,建议右键 templates 文件夹 → Mark Directory as → Templates Folder,以获得语法高亮与路径提示支持;
- 如仍报错,请检查当前工作目录是否为项目根目录(可通过 import os; print(os.getcwd()) 确认)。
? 小技巧:可通过 app.template_folder 查看 Flask 实际使用的模板路径:
print(app.template_folder) # 默认输出:'templates'
掌握这一约定,能避免绝大多数模板加载失败问题——记住:render_template() 的参数永远是“模板的逻辑路径”,而非磁盘物理路径。











