Flask中render_template('index.html')查找index.html文件

发布时间 2023-10-14 12:07:03作者: 凌波樂

问题:jinja2.exceptions.TemplateNotFound: index.html

解决方法如下:

普通:
render_template('index.html'),其中index.html的查询是找创建app = Flask(name)文件的同级目录的templates中查找

注意:
当导入create_app函数
from RealProject import create_app
app = create_app()
@app.route('/')
def hello_world():
return render_template('index.html') # 这时index.html还是要到包含create_app函数代码文件的同级目录的templates中查找

蓝图:

video.views.py 蓝图文件

from flask import Blueprint, render_template
bp = Blueprint('blog', name, url_prefix='/blog', static_folder='static', template_folder='templates')

def index():
return render_template('index.html') # 这里的index.html也是查询该文件的同级目录的templates中查找

注意:
这里的index视图函数,即使是其他py文件在创建create_app()函数中执行app.add_url_rule('/', endpoint='index', view_func=video.hello_world),
也是从video.views.py的同级目录的templates中查找,
而且需要注册video.bp蓝图,否则也找不到index.html
from app.video import views as video
app.register_blueprint(video.bp)