Home > Software engineering >  How to import variables in jinja2
How to import variables in jinja2

Time:09-17

I am trying to show the name of the user when the user log in and redirecting him to dashboard. I have passed the variable in /dashboard route but the user name is visible only in dashboard page. And when I route to different page eg., Home then the name of the user is not showing. I want to show the logged in user name in all pages but the user name is visible only in dashboard.

Here is the code from app.py

@app.route('/dashboard')
@login_required
def dashboard():
    return render_template('dashboard.html', name=current_user.user_name)

and this is my layout.html

<div class="account-info">
     {% if current_user.is_authenticated %}
     <span id="account-name"><a href="/dashboard">{{ name }}</a></span>
     {% else %}
     <span id="account-name"><a href="/dashboard">{{ dname }}</a></span>
     {% endif %}
</div>

here dname is the variable I am passing if the user is not logged in.

CodePudding user response:

I think you should consider using Session. Once your app captures and verifies the user you can store the username using session to allow it to be available across requests.

Please refer to this documentation: Flask Documentation on Session

CodePudding user response:

First Try This

You are only passing in the Username class, try passing in the whole class as well.

Next you can create a new route for autheticated users called home_auth or something like that and over ride the default home page to home_auth page.

In the home_auth page, you can pass in the Username and display it.

  • Related