Node.js、Express、EJS - 导航中当前页面上的活动类

2022-01-10 00:00:00 node.js express navigation javascript ejs

我想根据我在 layout.ejs 模板中的页面在每个导航链接上呈现一个当前"类.

I'd like to render a 'current' class on each of my navigation links depending on which page I'm on in my layout.ejs template.

目前,我的快速控制器索引如下所示:

Currently, my express controller index looks like this:

// About
exports.about = function(req, res) {
    res.render('content/about.ejs', {
        title: 'About'
    });
};

在我的 layout.ejs 中,我希望动态呈现以下内容.

And in my layout.ejs I have the following, which I'd like be rendered dynamically.

<ul class="nav" id="nav">
    <li><a href="/">Home</a></li>
    <li class="current"><a href="/about">About</a></li>
    <li><a href="/">Contact</a></li>
</ul>

关于如何实现这一点的任何想法?

Any ideas of how to achieve this?

推荐答案

你可以在 res.render 数据中包含一个 page_name: 'about' 然后在模板之类的:

You could include a page_name: 'about' in the res.render data and then in the template something like:

<li <% if (page_name === 'about') { %>class="current" <% } %> ><a href="/about">About</a></li>

我没有测试语法,但这就是要点.

I didn't test the syntax, but that's the gist.

相关文章