Skip to content Skip to sidebar Skip to footer

Node.js, Express, Ejs - Active Class On Current Page In Navigation

I'd like to render a 'current' class on each of my navigation links depending on which page I'm on in my layout.ejs template. Currently, my express controller index looks like this

Solution 1:

You could include a page_name: 'about' in the res.render data and then in the template something like:

<li <% if (page_name === 'about') { %>class="current" <% } %> ><ahref="/about">About</a></li>

I didn't test the syntax, but that's the gist.

Solution 2:

You can pass a variable to the page like this, and use a condition inside the class attribute.

<aclass="nav-link <%= page_name === 'home' && 'active' %>"href="#"
>
    Home
</a>

Solution 3:

@thataustin's answer is correct! but I lost the default class, so I found a way to keep the default class when it's not active. Hope it helps someone someday

<li            
    <% if (page_name === 'about') { %>
        class="nav-item current"
        <%} else { %>
        class="nav-item"
        <% } %> >
    <ahref="/about">About</a>
</li>

Solution 4:

Firstly, I have passed an object {navSelectTitle : "your-required-page-to-be-selected"} while rendering each page in the main app.js. Then, you can create a list in your ejs template like following:

<% const navItems = ["home", "articles", "videos", "audios"] %>

Then, you can loop through the list and add a class to make the link appear selected. (Here, I have used the class class="selected" to make the link appear selected)

Also, since I need my home page to have the href as href="/" and not <a href="/home", I have created a separate if statement for the case of "home" to accomodate this special case.

<% navItems.forEach(navlink => { %>
    <% if(navlink == navSelectTitle) { %>
        <% if (navlink == "home") {%>
            <liclass="links selected"><ahref="/"><%= navlink %></a></li>
        <% } else {%>
            <liclass="links selected"><ahref="/<%= navlink %>"><%= navlink %></a></li>
        <% } %>
                
    <% } else { %>
        <% if (navlink == "home") {%>
            <liclass="links"><ahref="/"><%= navlink %></a></li>
        <% } else {%>
            <liclass="links"><ahref="/<%= navlink %>"><%= navlink %></a></li>
        <% } %>
    <% } %>
<% }) %>

The code logic goes as follows:

  1. Loop through the list.
  2. If the list item equals to the object value that you passed while rendering the page, then the li tag will have the class="selected". If not, the else statement will create a normal link without the selected class.
  3. To accomodate the case where the home link should have href="/", there's a nested if-else statement inside the if statement for the said case.

NOTE: Using partial for the navigation bar can help dry your code and makes this logic a little convenient.

Post a Comment for "Node.js, Express, Ejs - Active Class On Current Page In Navigation"