1

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?

John Pogosyan
  • 11
  • 1
  • 2

3 Answers3

10

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
Michael Yin
  • 1,764
  • 13
  • 13
1

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;
}
Setthase
  • 13,988
  • 2
  • 27
  • 30
0

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
hexacyanide
  • 88,222
  • 31
  • 159
  • 162