使用Flask将变量传递给所有Jinja2模板 [英] Pass variables to all Jinja2 templates with Flask

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

问题描述

我的webapp的导航系统中有一张桌子,每次页面呈现时都会填充最新的信息。我怎样才能避免在每个视图中放置以下代码?

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

mydict 用于填充表格。这个表格会显示在每个页面上

解决方案

您可以使用 Flask的上下文处理器将全局变量插入到你的jinja模板中



这是一个例如:






$ b返回字典(mydict = code_to_generate_dict( ))




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


I have a table in the navigation system of my webapp that will be populated with up-to-date information each time a page is rendered. How could I avoid putting the following code in each view?

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

mydict is used to populate the table. The table will show up on each page

解决方案

You can use Flask's Context Processors to inject globals into your jinja templates

Here is an example:

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

这篇关于使用Flask将变量传递给所有Jinja2模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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