Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jade template conditional class nodejs expressjs

I have a jade template file for my header and uses bootstrap markup. Depending on what page the user is on, the navigation bar needs to add class .active to that nav item. What is the best way to do this avoiding long code like this.

header.jade

if nav=='home'
   li.active
      a(href="/") Home
else
   li
      a(href='/') Home
if nav=='about'
   li.active
      a(href='/about') About
else
   li
      a(href='/about') About

route

router.get('/about', function(req, res) {
   res.render('about', { nav:'about' });
});

Notice how if there are many more links in the header, it will get much longer. Is there a better method to add class 'active' to the page that is being viewed?

Thanks Tyler

like image 629
Tyler Evans Avatar asked Dec 30 '25 16:12

Tyler Evans


1 Answers

You could create a mixin that handles the rendering of a list item. This way your logic code does not have to be repeated:

mixin header-item(name, url)
  if name.toLowerCase() == nav
    li.active
      a(href=url)= name
  else
    li
      a(href=url)= name

+header-item('Home', '/')
+header-item('About', '/about')

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!