即使模板文件存在,Flask仍会引发TemplateNotFound错误 [英] Flask raises TemplateNotFound error even though template file exists
问题描述
我试图呈现文件 home.html
。该文件存在于我的项目中,但当我尝试渲染它时,我总是收到 jinja2.exceptions.TemplateNotFound:home.html
。为什么Flask无法找到我的模板?
from flask import Flask,render_template
app = Flask (__name__)
@ app.route('/')
def home():
return render_template('home.html')
$ b/ myproject
app.py
home.html
解决方案正确的位置;在你的python模块的
templates
子目录下。
错误表示没有
文件。确保你在你的python模块所在的目录下创建了这个目录,而且你确实在这个子目录中放了一个
templates /
目录中的home.htmlhome.html
文件。如果您的应用程序是一个包,则应该在包内部创建templates文件夹。myproject /
app.py
模板/
home.html
myproject /
mypackage /
__init__.py
模板/
home.html
< code $ <$ $ p
或者,如果您将模板文件夹命名为
templates
并且不想将其重命名为默认值,那么可以告诉Flask使用其他目录。app = Flask(__ name__,template_folder ='template')#仍然相对于模块
I am trying to render the file
home.html
. The file exists in my project, but I keep gettingjinja2.exceptions.TemplateNotFound: home.html
when I try to render it. Why can't Flask find my template?from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html')
/myproject app.py home.html
解决方案You must create your template files in the correct location; in the
templates
subdirectory next to your python module.The error indicates that there is no
home.html
file in thetemplates/
directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put ahome.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
这篇关于即使模板文件存在,Flask仍会引发TemplateNotFound错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!