我可以在我的EJS文档中使用条件语句在我的Node/Express应用程序的目录路径吗?



EJS新功能。我想做一个条件语句,如果我在这个目录路径上,那么替换导航栏中的这个链接。

<%let url = window.document.URL;
if(!url.includes('prospects/index')) {%>
<li class="nav-item">
<a class="nav-link" href="/prospects">Targeted Prospects</a>
</li>
<% } else { %>
<li class="nav-item">
<a class="nav-link" href="/prospects/new">Add Prospects</a>
</li>
<% } %>

我res.render

module.exports.index = async (req, res) => {
const prospects = await Prospect.find({});
res.render('prospects/index', { prospects })
};

我希望在我的路线上看到"前景/索引"我会看到"添加前景"以及所有其他的路线,我会看到"目标客户"。是否有一种方法可以在我的if语句中针对这条路线?谢谢!

您需要根据模板可访问的内容做出决定。可以在模板中使用的值来自传递给res.render的对象。这可能是请求的路径,就像你想到的:

res.render('prospects/index', {
prospects,
requestPath: req.path,
});
<% if (!requestPath.startsWith('/prospects/index')) %>

但是我更喜欢让路由器处理请求路径:

res.render('prospects/index', {
prospects,
isIndex: true,  // you might want to come up with a more descriptive name
})
<% if (!isIndex) %>

那么任何呈现相同模板的非索引路径都应该传递isIndex: false

相关内容

最新更新