res 未在 ejs 中定义

res is not defined in ejs

Objective: 我需要根据路由显示不同的模板。在我的例子中是 /edit /new,我需要一个条件来显示选项卡或其他东西。

在我的 router.get('/edit' cb) 中,我测试了这个: res.url.includes('new') 返回了 true。我进入了我的 header.ejs 和 运行 一个条件:

<% if(res.url.includes('new')) { %>
  <h1>Something else</h1>
<% } else { %>
  <h1>This</h1>
<% } %>

但是,它告诉我res 未定义。我的问题是:最好的方法是什么?我的第一直觉是创建另一个头文件,但这会重复很多代码,但我可能优化过度了。

你需要做res.render('template.ejs', { res: res });

检查你是否忘记传递 { res: res }