You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Node/Express应用的EJS模板中能否用条件语句控制导航链接?

精准匹配路由切换EJS导航链接的方案

问题分析

你当前用前端window.document.URL做模糊匹配的方式容易出现误判(比如其他路由包含prospects/index字符串时),而且EJS是服务端渲染模板,更推荐从服务端传递准确的路由路径给模板,实现精准匹配。

解决步骤

1. 服务端传递当前路由路径

修改所有路由的res.render代码,把请求的路径req.path作为模板变量传递进去,以你的index路由为例:

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

其他路由的res.render也需要添加currentPath: req.path,比如新增prospect的路由:

module.exports.new = (req, res) => {
  res.render('prospects/new', { currentPath: req.path })
};

2. EJS模板中精准判断路由

直接使用服务端传递的currentPath变量做严格相等判断,替换原来的模糊匹配逻辑:

<% if (currentPath !== '/prospects') { %>
  <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>
<% } %>

如果你的index路由实际路径是/prospects/index,就把判断条件改成currentPath === '/prospects/index'即可。

优势

  • 服务端传递的req.path是纯粹的路由路径,不会包含域名、查询参数等干扰内容,判断更精准。
  • 避免前端JS依赖,在模板渲染阶段就完成逻辑处理,更符合服务端渲染的场景。

内容的提问来源于stack exchange,提问作者Julius Evans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:23:22