Accessing the current user

Let's create links to the login and logout views in the navigation bar. To do this, we will need to check whether the current user is authenticated. If so, we will display a link to the logout view; otherwise, we will display a link to log in.

As you may recall from earlier in the chapter, we added a signal handler that stores the current user as an attribute of the Flask g object. We can access this object in the template, so we simply need to check, in the template, whether g.user is authenticated or not.

Open base.html and make the following additions to the navigation bar:

<ul class="nav navbar-nav"> <li><a href="{{ url_for('homepage') }}">Home</a></li> <li><a href="{{ url_for('entries.index') }}">Blog</a></li> {% if ...

Get Learning Flask Framework now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.