问题描述
我有一个布局翡翠视图,通过无序列表有一个菜单,我想将< li>
设置为当浏览器中显示当前页面时,li class =active> ...< / li>
我将不得不访问当前的请求,以确定何时设置属性在< li>
I找不到任何例子,如何做到这一点,希望有人可以帮助
谢谢
在您的路由中调用res.render()之前尝试这样做:
res.locals.path = req.path;
res.render('/ page');
或
res.render('/ page',{path:req.path});
然后,您将需要在视图中执行一堆if / else语句(如上面的解决方案建议)。
- if(currentUrl ==='/')
但是,我更愿意在客户端这样做,以使我的模板文件免于尽可能多的逻辑:
li(class ='active')
a(href ='/')当前驱动程序排名
- 否
li
a(href ='/')当前驱动程序排名
在页面模板文件(这是ejs,不知道如何回应玉):
< body data-path =<%= path%>>
然后使用jQuery可以从body获取路径并附加一个活动类:
$(function(){
var path = $('body')。attr('data-path');
$('nav li a [href ='+ path +']')。parents('li')。addClass('active');
});
更新:您还可以使用
var path = window.location.pathname
而不是将其保存到body
//不需要将路径保存到< body>标签第一:
$(function(){
var path = window.location.pathname;
$('nav li a [href ='+ path +']') .parents('li')。addClass('active');
});
I have a layout Jade view that has a menu via unordered list, and I want to set the
<li>
to be<li class="active">...</li>
when the current page is rendered in the browser.I assume I will have to access the current request to determine when to set the attribute on the
<li>
I can't find any examples of how to do this so hoping someone can help
Thanks
解决方案Try this before your call res.render() in your route:
res.locals.path = req.path; res.render('/page');
or
res.render('/page', { path: req.path });
Then you would have to do a bunch of if/else statements in your view (as the above solution suggests).
- if(currentUrl === '/') li(class='active') a(href='/') Current Driver Standings - else li a(href='/') Current Driver Standings
I however, prefer to do this on client side instead, to keep my template files free from as much logic as possible:
In page template file (this is ejs, not sure how to echo in jade):
<body data-path="<%= path %>">
Then with jQuery you can grab the path from body and attach an active class:
$(function(){ var path = $('body').attr('data-path'); $('nav li a[href='+path+']').parents('li').addClass('active'); });
Update: You can also just use
var path = window.location.pathname
instead of saving it to an attribute onbody
//no need to save path to <body> tag first: $(function(){ var path = window.location.pathname; $('nav li a[href='+path+']').parents('li').addClass('active'); });
这篇关于访问Express / Jade视图中的当前请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!