我有一个带蓝图的Flask应用程序.每个蓝图都提供了一些模板.当我尝试index.html从第二个蓝图渲染模板时,会渲染第一个蓝图的模板.为什么blueprint2会覆盖blueprint1的模板?如何渲染每个蓝图的模板?
app/
__init__.py
blueprint1/
__init__.py
views.py
templates/
index.html
blueprint2/
__init__.py
views.py
templates/
index.html
Run Code Online (Sandbox Code Playgroud)
blueprint2/__init__.py:
from flask import Blueprint
bp1 = Blueprint('bp1', __name__, template_folder='templates', url_prefix='/bp1')
from . import views
Run Code Online (Sandbox Code Playgroud)
blueprint2/views.py:
from flask import render_template
from . import bp1
@bp1.route('/')
def index():
return render_template('index.html')
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
如果我更改了蓝图的注册顺序,那么blueprint2的模板会覆盖蓝图1.
application.register_blueprint(bp2)
application.register_blueprint(bp1)
Run Code Online (Sandbox Code Playgroud)
尽管没有您期望的那样,但这与预期完全一致.
为蓝图定义模板文件夹仅将文件夹添加到模板搜索路径.它并不意味着将呼叫render_template从一个蓝图的视图将只检查该文件夹.
首先在应用程序级别查找模板,然后按顺序查看蓝图.这样,扩展可以提供可以被应用程序覆盖的模板.
解决方案是在模板文件夹中使用单独的文件夹,以获取与特定蓝图相关的模板.它仍然可以覆盖它们,但更难以意外地这样做.
app/
blueprint1/
templates/
blueprint1/
index.html
blueprint2/
templates/
blueprint2/
index.html
Run Code Online (Sandbox Code Playgroud)
render_template('blueprint1/index.html')
Run Code Online (Sandbox Code Playgroud)
有关更多讨论,请参阅Flask问题#1361.
Mal*_*415 -1
我依稀记得很早就遇到过这样的麻烦。您尚未发布所有代码,但我根据您所写的内容有四个建议。尝试第一个,测试它,然后如果它仍然不起作用,请尝试下一个,但独立测试它们以查看它们是否有效:
首先,我看不到您的views.py文件,因此请确保您在文件中导入了适当的蓝图views.py:
from . import bp1 # in blueprint1/views.py
from . import bp2 # in blueprint2/views.py
Run Code Online (Sandbox Code Playgroud)
其次,您可能需要按如下方式修复相对导入语句__init__.py(请注意子文件夹之前的句点):
from .blueprint1 import blueprint1 as bp1
from .blueprint2 import blueprint2 as bp2
Run Code Online (Sandbox Code Playgroud)
第三,由于您在函数中对模板的路径进行了硬编码,因此请尝试从蓝图定义中render_template删除。template_folder='templates'
第四,看起来您在注册时将蓝图的 url_prefix 命名为“/bp1”。因此,如果到您的文件系统的硬编码链接仍然不起作用:
render_template('blueprint1/index.html')
Run Code Online (Sandbox Code Playgroud)
然后也尝试一下,看看会发生什么:
render_template('bp1/index.html')
Run Code Online (Sandbox Code Playgroud)
同样,我看不到您的完整代码,但我希望这会有所帮助。
| 归档时间: |
|
| 查看次数: |
1552 次 |
| 最近记录: |