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

前端 未结 7 819
刺人心
刺人心 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 07:01

    Similar to @netAction's post, but dependent on the URL and not on the title.

    each menuitem in [{title:'Home',url:'/'},{title:'About',url:'/about'},{title:'Contact',url:'/contact'}]
        if (path == menuitem.url)
            li.active
                a.active(href=menuitem.url) #{menuitem.title}
        else
            li
                a(href=menuitem.url) #{menuitem.title}
    

    Combined with

    app.use(function(req, res, next) {
        res.locals = {
            isAuthenticated: req.isAuthenticated(),
            path :req.path
        }
    
        next(); // make sure we go to the next routes and don't stop here
    });
    
    0 讨论(0)
提交回复
热议问题