EJS conditional rendering

All we need is an easy explanation of the problem, so here it is.

How to render html if user is logged in or not. I have tried if, else but it doesn’t work as i want it to be. Is there another way of doing the same.

    <% if(typeof(user) === "defined" ){ %>
      <li class="navlist-item user">
        <a href="/user/<%= user.id %> "> <i class="far fa-user"> <%= user.name %> </i> </a>
      </li>
  <% } %>
  <% if(typeof(user) != "undefined" ){ %>
          <li class="navlist-item">
            <span class="get-started">
              <a href="/auth/register"> Sign Up</a>
            </span>
          </li>
          <li class="navlist-item">
            <span class="get-started">
              <a href="/auth/login">
                <span> Log In</span>
              </a> </span>
 <% } %> 

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

 <% if(typeof user !== 'undefined'){ %>
      <li class="navlist-item user">
        <a href="/user/<%= user.id %> "> <i class="far fa-user"> <%= user.name %> </i> </a>
      </li>
  <% } else { %>
          <li class="navlist-item">
            <span class="get-started">
              <a href="/auth/register"> Sign Up</a>
            </span>
          </li>
          <li class="navlist-item">
            <span class="get-started">
              <a href="/auth/login">
                <span> Log In</span>
              </a> </span>
 <% } %>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

Leave a Reply