【问题标题】:Provide standard data to Flask template向 Flask 模板提供标准数据
【发布时间】:2019-11-08 11:24:46
【问题描述】:

我希望能够根据对象的内容生成导航栏,基本上有一个导航栏数组或类来保存子页面并生成带有折叠部分等的适当导航栏。我在 PHP 中使用 Laravel 的经验类似于烧瓶,但我想不出一种容易做到的方法。我必须为每个页面提供一组数据对象,因为它是布局的一部分,但我不想为每个页面专门指定它。有没有办法做到这一点?

到目前为止,我只有基础知识、应用工厂、视图和蓝图:

工厂

def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')

    app.register_blueprint(blueprint_index)

    return app

蓝图

from flask import Blueprint, render_template, session

blueprint_index = Blueprint('simple_page', __name__)


@blueprint_index.route('/')
def index():
    if 'text' in session:
        session['text'] += 1
    else:
        session['text'] = 0
    return render_template('pages/index.html', text=str(session['text']))

忽略我添加到路由中的一点调试文本。

【问题讨论】:

标签: python templates flask


【解决方案1】:

您可以使用上下文处理器来执行此操作。将此添加到您的蓝图代码块的末尾:

@blueprint_index.context_processor
def inject_text():
    return dict(text=session['text'])

{{text}} 现在可以在该蓝图上的每个模板中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 2011-07-08
    • 1970-01-01
    • 2012-12-09
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多