问题
I have a navigation bar in my parent jade template and I'd like to highlight the item which is currently in view. So if I'm on the blog page,
ul
li Home
li.active Blog
li Contact Us
li About
Without copying the navigation bar structure into each child template, is there a way to have the parent template see what page it's extending and apply the active
class accordingly?
回答1:
parent.jade
doctype 5
html
block link
-var selected = 'home'; //default
-var menu = { 'home': '/home', 'blog': '/blog', 'contact': '/contact' };
body
nav
ul
each val, key in menu
li
if selected === key
a.selected(href=val, title=key)= key
else
a(href=val, title=key)= key
child.jade
extends parent
block link
-var selected = 'blog';
回答2:
Here's a simpler way:
Use this in your layout.jade (where nav
is the name of the page that's active. nav = 'about' for example)
ul(class="#{nav}")
li.home Home
li.blog Blog
li.contact Contact Us
li.about About
Then put this is your CSS:
ul.home li.home,
ul.blog li.blog,
ul.contact li.contact,
ul.about li.about {
color: red;
}
The only css rule that will apply is the one whose ul
class exists. You'll need to pass in a variable nav
that equals 'about', 'home', 'contact', or 'blog' depending on what page you're on.
回答3:
Use the Current object with a ternary expression. All is in the documentation.
You can use the object properties to generate your active menu like so. If you want to use folders in your navigation menu (Jade version) :
ul(class="nav-menu")
li: a(class="#{ current.path[0] === 'index' ? 'active' : '' }", href="/") home
li: a(class="#{ current.path[0] === 'about' ? 'active' : '' }", href="/about/") about
回答4:
Well, above solution is very clear but if someone is looking more controls over menus then there is a module available for node.js. Use this and you would have complete control over menus.
Use Case : When menus visibles based on roles
https://www.npmjs.com/package/active-menu
来源:https://stackoverflow.com/questions/15719660/jade-change-active-menu-item-in-parent-template