1

我目前正在学习 nodejs,我的 .ejs 模板文件非常标准(页眉、页脚、js-defaults 等)——唯一改变它的是 HTML div 中的内容。

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

在 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>
4

1 回答 1

2

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

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

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

app.set('view cache', false);
于 2015-01-24T03:20:56.173 回答