Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables to all Jinja2 templates with Flask

Tags:

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

like image 545
Brian Leach Avatar asked Jul 31 '15 16:07

Brian Leach


People also ask

How do you pass data into a template in Flask?

Flask sends form data to template Flask to send form data to the template we have seen that http method can be specified in the URL rule. Form data received by the trigger function can be collected in the form of a dictionary object and forwarded to the template to render it on the corresponding web page.

Can we inherit templates in Flask?

Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. Sounds complicated but is very basic. It's easiest to understand it by starting with an example.


1 Answers

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:

like image 139
Josh J Avatar answered Sep 30 '22 15:09

Josh J