【问题标题】:render_template from Flask blueprint uses other blueprint's templateFlask 蓝图中的 render_template 使用其他蓝图的模板
【发布时间】:2016-07-06 09:27:17
【问题描述】:

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

如果我更改蓝图的注册顺序,那么 blueprint2 的模板会覆盖 blueprint1。

application.register_blueprint(bp2)
application.register_blueprint(bp1)

【问题讨论】:

  • 你应该发布你的__init__.py文件。
  • 谢谢,现已发布。
  • 我猜问题出在Blueprint('bp1', ...你应该注册目录的全名就像Blueprint('blueprint1',一样
  • 不是这样的,我改了名字但是没有任何新的事情发生。我发现我注册蓝图的顺序决定了显示哪个页面。我注册的第一个将覆盖第二个模板。
  • 您是否尝试过更改template_folder='templates'?也许到template_folder='blueprint2/templates'?还是给它一个完整的路径?

标签: python flask


【解决方案1】:

这完全按预期工作,但与您的预期不同。

为蓝图定义模板文件夹只会将该文件夹添加到模板搜索路径中。它确实意味着从蓝图视图调用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

【讨论】:

    【解决方案2】:

    我隐约记得在早期遇到过这样的问题。您尚未发布所有代码,但根据您所写的内容,我有四个建议。尝试第一个,测试它,然后如果它仍然不起作用,尝试下一个,但独立测试它们是否有效:

    首先,我看不到您的 views.py 文件,因此请确保您在 views.py 文件中导入了适当的蓝图:

    from . import bp1   # in blueprint1/views.py
    from . import bp2   # in blueprint2/views.py
    

    其次,您可能需要将__init__.py 中的相关导入语句修复如下(注意子文件夹前面的句点):

    from .blueprint1 import blueprint1 as bp1
    from .blueprint2 import blueprint2 as bp2
    

    第三,由于您在 render_template 函数中硬编码模板的路径,请尝试从蓝图定义中删除 template_folder='templates'

    第四,您在注册时将蓝图的 url_prefix 命名为“/bp1”。因此,如果您的文件系统的硬编码链接仍然不起作用:

    render_template('blueprint1/index.html')
    

    然后也试试这个,看看会发生什么:

    render_template('bp1/index.html')
    

    同样,我看不到您的完整代码,但我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多