Node.js, Express, EJS - Active class on current page in navigation

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

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

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" <% } %> ><a href="/about">About</a></li>

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


@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"
        <% } %> >
    <a href="/about">About</a>
</li>