我有一个带有蓝图的 Flask 应用程序。每个蓝图都提供了一些模板。当我尝试从第二个蓝图渲染 index.html
模板时,会渲染第一个蓝图的模板。为什么 blueprint2 覆盖 blueprint1 的模板?如何渲染每个蓝图的模板?
app/
__init__.py
blueprint1/
__init__.py
views.py
templates/
index.html
blueprint2/
__init__.py
views.py
templates/
index.html
blueprint2/__init__.py
:
from flask import Blueprint
bp1 = Blueprint('bp1', __name__, template_folder='templates', url_prefix='/bp1')
from . import views
blueprint2/views.py
:
from flask import render_template
from . import bp1
@bp1.route('/')
def index():
return render_template('index.html')
app/__init__.py
:
from flask import Flask
from blueprint1 import bp1
from blueprint2 import bp2
application = Flask(__name__)
application.register_blueprint(bp1)
application.register_blueprint(bp2)
如果我更改蓝图的注册顺序,则蓝图 2 的模板会覆盖蓝图 1 的模板。
application.register_blueprint(bp2)
application.register_blueprint(bp1)
最佳答案
这完全按预期工作,尽管不是您预期的那样。
为蓝图定义模板文件夹只会将文件夹添加到模板搜索路径。它不意味着从蓝图 View 调用render_template
只会检查该文件夹。
首先在应用程序级别查找模板,然后按照注册蓝图的顺序查找。这样一来,扩展程序就可以提供可以被应用程序覆盖的模板。
解决方案是在模板文件夹 中为与特定蓝图相关的模板使用单独的文件夹。仍然可以覆盖它们,但不小心这样做就更难了。
app/
blueprint1/
templates/
blueprint1/
index.html
blueprint2/
templates/
blueprint2/
index.html
将每个蓝图指向其 templates
文件夹。
bp = Blueprint('bp1', __name__, template_folder='templates')
渲染时,指向templates
文件夹下的具体模板。
render_template('blueprint1/index.html')
参见 Flask issue #1361进行更多讨论。
关于python - Flask 蓝图中的 render_template 使用其他蓝图的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38220574/