在Express / Jade视图中访问当前请求

我有一个布局的Jade视图,通过无序列表的菜单,并且当浏览器中呈现当前页面时,我想将<li>设置为<li class="active">...</li>

我假设我将不得不访问当前请求来确定何时在<li>上设置属性

我找不到如何做到这一点,希望有人能帮助的例子

谢谢

在你的路由中调用res.render()之前试试这个:

 res.locals.path = req.path; res.render('/page'); 

要么

 res.render('/page', { path: req.path }); 

那么你将不得不在你的视图中做一堆if / else语句(如上面的解决scheme所示)。

 - if(currentUrl === '/') li(class='active') a(href='/') Current Driver Standings - else li a(href='/') Current Driver Standings 

然而,我宁愿在客户端做这件事,以保持我的模板文件免受尽可能多的逻辑:

在页面模板文件(这是ejs,不知道如何回声在玉):

 <body data-path="<%= path %>"> 

然后用jQuery,你可以从正文中获取path并附加一个活动类:

 $(function(){ var path = $('body').attr('data-path'); $('nav li a[href='+path+']').parents('li').addClass('active'); }); 

更新:你也可以使用var path = window.location.pathname而不是将其保存到body上的属性

 //no need to save path to <body> tag first: $(function(){ var path = window.location.pathname; $('nav li a[href='+path+']').parents('li').addClass('active'); }); 

在服务器端,这是一个更好的方法:

在您的routes.js (或任何地方)定义一个代表您的导航的对象数组,像这样:

 var navLinks = [ { label: 'Home', key: 'home', path: '' }, { label: 'About', key: 'about', path: '/about' }, { label: 'Contact', key: 'contact', path: '/contact' } ] 

navLinksvariables传递给您的视图,以及您希望的项目的键:

 res.render('home', { title: 'Welcome!', section: 'home', navLinks: navLinks }); 

您还可以将navLinksvariables添加到app.locals并保存自己始终必须明确地将其提供给视图。

然后在你的玉模板循环通过链接数组并设置主键匹配提供的部分的活动类:

 ul(class='nav nav-list') - navLinks.forEach(function(link){ - var isActive = (link.key == section ? 'active' : '') li(class=isActive) a(href=link.path)= link.label - }) 

传递你的路线文件中的req.originalUrl。 例如:在你的/routes/about.js中

 router.get('/', function(req, res) { res.render('about', { url: req.originalUrl }); }); 

然后,在你的玉模板上写上if else条件

  if(url==='/about-us') li(class='active') a(href='about-us') About Us else li a(href='about-us') About Us 

我想出了这个工作,但我不知道,如果它的最佳做法。 请让我知道任何一种方式:

 response.render("current/currentSchedule", { title: "Current Race Schedule", currentUrl: req.path, }); ul(class='nav nav-list') li(class='nav-header') Current Season - if(currentUrl === '/') li(class='active') a(href='/') Current Driver Standings - else li a(href='/') Current Driver Standings - if(currentUrl === '/constructor-standings') li(class='active') a(href='/constructor-standings') Current Constructor Standings - else li a(href='/constructor-standings') Current Constructor Standings - if(currentUrl === '/current-schedule') li(class='active') a(href='/current-schedule') Current Race Schedule - else li a(href='/current-schedule') Current Race Schedule