Pass variables to all Jinja2 templates with Flask

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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

回答1:

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:



回答2:

Write your own render method do keep yourself from repeating that code. Then call it whenever you need to render a template.

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')


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!