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

前端 未结 7 816
刺人心
刺人心 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:45

    I think it's better to set a body class to current path like so

    body(class = currentPath)
    

    So you can then use selectors such as

    body.home .nav li.home, body.dashboard .nav li.dashboard {
      Style when current path
    }
    

    These selectors can be reduced to the minimal 'body.path .path' but it may be not isolated enough.

    This will also be useful in the client side logic as this selectors could be used to determine the path in your JavaScript with something like

    $("body.home").doSomethingSpecificToHome
    

    This way your template has lot less logic.

    Now, I don't think there is a way to set "currentPath" automatically depending on the URL. An helpers based on a 'url':'path' may be useful.

提交回复
热议问题