Flask + Jinja:将数据传递给基本模板/所有模板 [英] Flask + Jinja: Pass Data to a Base Template/All Templates

查看:105
本文介绍了Flask + Jinja:将数据传递给基本模板/所有模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



(1)如何将一个变量传递给一个变量基本模板(其他模板扩展)或(2)将变量全局传递给所有模板,而不必在调用 render_template

解决方案

来自flask文档: http://flask.pocoo.org/docs/0.10/templating/#context-processors


要将新变量自动注入到模板的上下文中,
上下文处理器存在于Flask中。上下文处理器在呈现
模板之前运行,并且能够将新值注入
模板上下文中。上下文处理器是一个返回
字典的函数。然后将这个字典的键和值合并到
与模板的上下文中,在应用程序中的所有模板中:

从文档:

  @ app.context_processor 
def inject_user():
return dict(user = g .user)

注意这个例子使用 g 变量,已经可以在模板中访问了。


I have a method that returns data which is needed in my base template (content for a global footer).

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?

解决方案

From flask docs: http://flask.pocoo.org/docs/0.10/templating/#context-processors

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:

Example from docs:

@app.context_processor
def inject_user():
    return dict(user=g.user)

Note that this example uses the g variable, which is already accessible in templates.

这篇关于Flask + Jinja:将数据传递给基本模板/所有模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆