Skip to content
Advertisement

How to use {% if user.is_authenticated %} in html to display or remove content

I’m trying to display certain content in my navbar when a user is logged in, but {% if user.is_authenticated %} does not work when I add it to my HTML

<div class="collapse navbar-collapse" id="navbar">
  <ul class="navbar-nav mr-auto">
    {% if request.user.is_authenticated %}
    <li class="nav-item active">
      <a class="nav-item nav-link" id="home" href="/home">Home</a>
    </li>
    <li class="nav-item active">
      <a class="nav-item nav-link" id="logOut" href="/logout">Log-out</a>
    </li>
    {% else %}
    <li class="nav-item active">
        <a class="nav-item nav-link" id="login" href="/login">Login</a>
    </li>
      <li class="nav-item active">
        <a class="nav-item nav-link" id="signUp" href="/sign-up">Sign-up</a>
      </li>
    {% endif %}  
  </ul>

Advertisement

Answer

Flask-Login adds the current_user variable to your templates

{% if current_user.is_authenticated %}
    ...
{% else %}
    ...
{% endif %}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement