Jade: Change active menu item in parent template

天涯浪子 提交于 2019-11-28 17:01:50

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';
Costa

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.

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!