Flask框架jinja2.exceptions.TemplateNotFound异常求助:已创建模板文件夹仍报错
解决Jinja2 TemplateNotFound 异常问题
我一眼就揪出了问题的根源——你在调用render_template()的时候多写了一层templates/前缀!
你已经在初始化Flask应用时指定了template_folder='templates',这就相当于告诉Flask:“去这个文件夹里找我的模板文件”。结果你调用render_template("templates/index.html")时,Flask会傻乎乎地去寻找templates/templates/index.html这个不存在的路径,自然就抛出了找不到模板的异常。
只需要把返回语句里的模板路径改成index.html就能解决问题,修改后的home()函数代码如下:
@app.route("/") def home(): return render_template("index.html")
额外提个小技巧:其实你完全可以不用手动指定template_folder='templates',因为Flask默认就会在名为templates的文件夹里查找模板文件,这是它的默认约定。所以你也可以把应用初始化代码简化成app = Flask(__name__),功能完全不受影响。
内容的提问来源于stack exchange,提问作者M Zain-ul-Abideen
相关产品推荐
相关产品推荐

