Flask + Jinja:将数据传递到基本模板/所有模板 [英] Flask + Jinja: Pass Data to a Base Template/All Templates
问题描述
我有一个方法可以返回我的基本模板(全局页脚的内容)中所需的数据.
I have a method that returns data which is needed in my base template (content for a global footer).
如何 (1) 将变量传递到基本模板(其他模板扩展)或 (2) 将变量全局传递给所有模板,而无需在对 render_template
的调用中显式添加它?
How do either (1) pass a variable into the base template (which other templates extend) or (2) pass a variable to all templates globally without explicitly adding it in a call to render_template
?
推荐答案
来自flask 文档:Flask 的上下文处理器
From flask docs: Flask's Context Processors
要自动将新变量注入模板的上下文中,Flask 中存在上下文处理器.上下文处理器在模板被渲染并能够将新值注入模板上下文.上下文处理器是一个函数,它返回一个字典.然后合并此字典的键和值使用模板上下文,对于应用中的所有模板:
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:
来自文档的示例:
@app.context_processor
def inject_user():
return dict(user=g.user)
请注意,此示例使用了 g
变量,该变量已可在模板中访问.
Note that this example uses the g
variable, which is already accessible in templates.
这篇关于Flask + Jinja:将数据传递到基本模板/所有模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!