Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a "encapsulated" fragments in Jinja

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

enter image description here

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

like image 496
Alex Avatar asked Dec 29 '25 09:12

Alex


1 Answers

Use template inheritance to show the user section on all pages. You will have:

  • base template (the frame with the current user section and a space for the content below)
  • child templates (each of the pages which show, in the top right, the user section

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' %}
like image 132
miquelvir Avatar answered Jan 01 '26 01:01

miquelvir