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:

// About
exports.about = function(req, res) {
    res.render('content/about.ejs', {
        title: 'About'

And in my layout.ejs I have the following, which I’d like be rendered dynamically.

<ul class="nav" id="nav">
    <li><a href="/">Home</a></li>
    <li class="current"><a href="/about">About</a></li>
    <li><a href="/">Contact</a></li>

Any ideas of how to achieve this?


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.

Answered By – thataustin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published