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

2024-05-14 01:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在webapp的导航系统中有一个表,每次呈现页面时都会填充最新的信息。我如何避免在每个view中放入以下代码?

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

mydict用于填充表。这张桌子将出现在每页上


Tags: to代码view信息returndefcode页面
2条回答

编写您自己的呈现方法不要重复该代码。然后在需要呈现模板时调用它。

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将全局变量注入您的jinja模板

下面是一个例子:

@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:

相关问题 更多 >