使用 Flask 将变量传递给所有 Jinja2 模板

Pass variables to all Jinja2 templates with Flask

我的网络应用程序的导航系统中有一个 table,每次呈现页面时都会填充最新信息。我怎样才能避免将以下代码放入每个 view?

def myview():
    mydict = code_to_generate_dict() 
    return render_template('main_page.html',mydict=mydict)

mydict用于填充table。 table 将显示在每个页面上

编写您自己的呈现方法可以避免重复该代码。然后在需要渲染模板时调用它。

def render_with_dict(template):
    mydict = code_to_generate_dict() 
    return render_template(template, mydict=mydict)

def myview():
    return render_with_dict('main_page.html')

您可以使用 Flask's Context Processors 将全局变量注入到您的神社模板中

这是一个例子:

@app.context_processor
def inject_dict_for_all_templates():
    return dict(mydict=code_to_generate_dict())

To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app: