python - Flask 蓝图中的 render_template 使用其他蓝图的模板

标签 python flask

我有一个带有蓝图的 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/

相关文章:

python - 在启动/重启 AWS 实例时运行 Python 脚本

python - 提交表单后重定向到其他 View

python - 在 pyqt 中显示运行时输出

python - 使用 Python/Matplotlib 基于颜色图绘制(极坐标)色轮

python - 代码不会停止运行。看起来微不足道,但我无法弄清楚

python - 如何从作为 Windows pywin32 服务运行的 flask 和女服务员中干净地退出

python - AWS python Flask EB .ebextensions .conf 文件不工作

python - 在 python 3.3 列表中查找最小值

python - 如何使用 setuptools 将 css 文件打包为单模块 Flask 应用程序?

jquery - WTForms 与 Jquery Form Plugin 耦合时如何显示验证错误?