嵌入式 JavaScript (EJS) - 从路由动态设置视图



我现在正在学习nodejs,我的.ejs模板文件几乎是标准的(页眉,页脚,js默认值等) - 唯一改变它的东西是HTMLdiv中的内容。

我想我可以在我的路线中设置一个变量并将其传递给视图(就像标题或其他变量一样),然后包含它 - 但它不起作用(下面的示例)。

在 Ruby 中,你可以用"yield"来做到这一点,我正在尝试用 EJS 做同样的事情。

感谢您抽出宝贵时间阅读(请原谅我在这件事上的无知)。

示例路由

app.get('/fish', function(req, res) {
res.render('fish' {
    title:"Fish",
    template:"view/partials/content/fish.ejs"
});

});

示例 EJS

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<% include views/partials/template/header.ejs %>
<body>
    <div class="container">
      <!-- Dynamic content here -->
      <% include template %> <!-- tries to load template.ejs %>
    </div>
</body>
<% include views/partials/template/footer.ejs %>
<% include views/partials/template/js-defaults.ejs %>
</html>

看起来EJS现在支持此功能。它在 v2.0.1 中引入:2015-01-02。新语法如下所示

 <!-- Dynamic content here -->
      <%- include(template) %>

为了使它工作,我必须通过设置来禁用 Express 中的缓存:

app.set('view cache', false);

最新更新