I have a tiny Flask + Jinja app which need to have a common header with a user section (see bellow).

Now, this section must appear on any page and as it must contains user's name I wonder if there is any way to avoid passing user details (see user variable bellow) for every rendered page.
...
return render_template('home.html', user=userDetails, entries=entriesList, bla=blaValue)
I know PHP and JSP allows you to create "encapsulated" fragments that have their own local logic but I wonder if the same can be achieved with Jinja (and Flask).
Use template inheritance to show the user section on all pages. You will have:
Then in flask you will need to pass user=userDetails for every template. If you want to encapsulate that, just do something like this:
from flask_login import current_user
def render_template_with_user(*args, **kwargs):
"""renders the template passing the current user info"""
return render_template(*args, user=current_user, **kwargs)
You can also use the include statement for importing templates somewhere in a parent template.
{% include 'header.html' %}
Body
{% include 'footer.html' %}
You can combine it with the with statement to pass some variables to the included component.
{% with username = user.name %} {% include 'header.html' %} {% endwith %}
Body
{% include 'footer.html' %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With