0

So I have this Flask app that I need a pass a particular user to all routes as all pages in the app will be needing the particular user to render templates. I don't want to pass the user as it's normal done

return render_template('index.html',user=user) 

Because I'd have to repeat the same thing for all routes in the render_templates. Please how can I do this?

3
  • Where does the variable user originates from or where does the variable is set? inside the function or globally? Commented Jul 3, 2021 at 13:01
  • The user is actually global since it's imported. The issue how to send it across all pages via the render_template function. More like a default argument for render_template Commented Jul 3, 2021 at 13:04
  • you can use global var, which are automatically available in templates flask.palletsprojects.com/en/2.0.x/tutorial/templates/… Commented Jan 12, 2022 at 23:06

2 Answers 2

4

You can do so by creating a custom render template function using the following implementation

from flask import render_template as real_render_template from yourapp import user # Import the user variable or set it def render_template(*args, **kwargs): return real_render_template(*args, **kwargs, user=user) 

it can also be done via functools.partial:

from flask import render_template as real_render_template from yourapp import user # Import the user variable or set it from functools import partial render_template = partial(real_render_template, user=user) 
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to send a variable to all routes/pages/templates. You can use sessions in flask

from flask import Flask,session [...] session['x'] = user 

Now you can use it anywhere in the code, templates using session['x']

In templates

{{session['x']}} 

2 Comments

Will the session variable be available in the templates file automatically? For instance the url_for function is that way due to jinja2 config with flask
Yes once you define in flask it will be available. You need to define a secret_key too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.