node.js + jade + express: How can I create a navigation that will set class active if the path matches

前端 未结 7 827
刺人心
刺人心 2021-01-31 06:31

I have come up with the following code but the problem is, there will be duplication of the anchor tag for each menu item.Is there a better way to do this?

              


        
7条回答
  •  遥遥无期
    2021-01-31 06:46

    Here's an alternative that provides more flexibility in terms of anchor text and href than Peter's solution.

    nav
      // suppose title local denotes the active nav item
      - var nav = {}; nav[title] = 'active'
      ul
        // pass title to li class via nav object
        li(class='#{nav.Home}')
          // different href and anchor text
          a(href='/') Home
        li(class='#{nav.About}')
          a(href='/about') About
        li(class='#{nav.Contact}')
          a(href='/contact') Contact
    

    The caveat is that those li that are not active will have an undefined class, which does no harm in most cases.

提交回复
热议问题