21

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

0

3 Answers 3

39

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:

Sign up to request clarification or add additional context in comments.

6 Comments

So it's not confusing for others, maybe mention that Flask is looking for a dict to be returned, whether my variable to be injected is a string, list, or any other datatype (including a dict)
Josh J, you are right, but i have problem with project with more views files. How can i implement context_processor in more files? Context_processor must be in all files or can i use more systematic solution? Thank you.
@lukassliacky context_processor is on the Flask application object so it works for any view processed by that application. If you have multiple applications, then you would need to repeat it.
One per Flask instance (app = Flask(...)). If those views are all serviced by the previous app, then they share context.
Thanks, I solved my problem for the generic menu :)
|
1

Instead of a decorator, you can pass a function where the necessary context processor will be

app = Flask(__name__) app.context_processor(templatetags) def templatetags(): def format_price(amount, currency="€"): return f"{amount:.2f}{currency}" return dict( format_price=format_price, ) 

'index.html'

{{ format_price(0.33) }} 

Comments

0

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

1 Comment

Josh's answer did not require that I modify all of my existing templates

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.