John Pogosyan
John Pogosyan

Reputation: 11

Node.js Express + Jade (Active Class on Lined Item)

How would I set an active tag to a class depending on the URL?

In the example below '/' (Home) is set to active.

.nav-collapse.collapse
  ul.nav.top-2
    li.active
      a(href='/') Home
    li
    li
      a(href='/about') About
    li
    li
      a(href='/contact') Contact
    li

Would it be better to inject something into the page to identify it as the active page?

Upvotes: 1

Views: 3040

Answers (3)

Michael Yin
Michael Yin

Reputation: 1754

Here's what I do, like hexacyanide's example,

res.render('/path', {
  path: req.path
});

..and in layout.jade:

.nav-collapse.collapse
  ul.nav.top-2
    li(class=path=='/'?'active':undefined)
      a(href='/') Home
    li(class=path=='/about'?'active':undefined)
      a(href='/about') About
    li(class=path=='/contact'?'active':undefined)
      a(href='/contact') Contact

Upvotes: 10

Setthase
Setthase

Reputation: 14398

You can also consider adding id to body tag, with will be telling you on what page you are. And then you can specify simple CSS rules dependent of that id. It's very popular scheme, for example provided by Wordpress.

For this id you can use Jade variable provided by render method.

In your express code:

res.render('/', { id : 'home' });

In template:

body##{id}

and later in ul.nav

li.home
  a(href='/') Home
li
li.about
  a(href='/about') About
li
li.contact
  a(href='/contact') Contact

In CSS:

#home ul.nav li.home {
    background: red;
}

#about ul.nav li.about {
    background: red;
}

Upvotes: 1

hexacyanide
hexacyanide

Reputation: 91679

Take a look at Jade's conditionals, documented on GitHub. You would want to pass the path to the render in Express like so:

res.render('/path', {
  path: req.path
});

Then in Jade, you would use a conditional like so:

if path == 'home'
  //active styling
else
  //not active

Upvotes: 0

Related Questions