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
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')
来源:https://stackoverflow.com/questions/24451878/jade-template-conditional-class-nodejs-expressjs