您必须在正确的位置创建模板文件。在templates
您的python模块旁边的子目录中。
The error indicates that there is no home.html
file in the templates/
directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a home.html
file in that subdirectory. If your app is a package, the templates folder should be created inside the package.
myproject/
app.py
templates/
home.html
myproject/
mypackage/
__init__.py
templates/
home.html
Alternatively, if you named your templates folder something other than templates
and don't want to rename it to the default, you can tell Flask to use that other directory.
app = Flask(__name__, template_folder='template') # still relative to module
You can ask Flask to explain how it tried to find a given template, by setting the EXPLAIN_TEMPLATE_LOADING
option to True
. For every template loaded, you'll get a report logged to the Flask app.logger
, at level INFO
.
搜索成功后的样子:在此示例中,foo/bar.html
模板扩展了base.html
模板,因此有两个搜索:
[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/base.html')
蓝图也可以注册自己的模板目录,但这不是必需的,如果您使用蓝图可以更轻松地在逻辑单元之间拆分较大的项目。即使在每个蓝图中使用其他路径,也始终会首先搜索Flask应用程序主模板目录。
EXPLAIN_TEMPLATE_LOADING对于调试模板周围的路径问题非常有用。另外,如果您使用“蓝图”,请确保设置“ 每蓝图 ”
template_folder
路径。@JustinKrause:谢谢您,
EXPLAIN_TEMPLATE_LOADING
在最初编写此答案后添加了这些内容。好像我的本地烧瓶(在Windows上)可以在中找到模板
./Templates/index.html
,但是当我部署到heroku时(认为它是相同的Python,相同的库版本,包括相同的Flask版本;但是heroku是Unix);并引发TemplateNotFound
错误;重命名文件夹后git mv Templates/index.html templates/index.html
,本地(Windows)和heroku(Unix)版本都可以使用@TheRedPea是的,因为Windows文件系统折叠大小写,所以
Templates
==templates
。但是Heroku使用区分大小写的文件系统运行Linux。