Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
</ul>

Any ideas of how to achieve this?

like image 730
devopix Avatar asked Nov 21 '14 01:11

devopix


People also ask

How do I navigate to another page in EJS?

As illustrated in the image above, the best way to navigate different web pages using ejs template is to ensure you create a folder called "partials" in your project's "views folder directory" where you have your other ejs files. 1) Then in that "partials folder" create 2 separate ejs files called header. ejs & footer.


1 Answers

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.

like image 120
thataustin Avatar answered Sep 18 '22 21:09

thataustin