【问题标题】:Embedded JavaScript (EJS) - Dynamically setting view from route嵌入式 JavaScript (EJS) - 从路由动态设置视图
【发布时间】:2015-01-24 11:20:56
【问题描述】:

我现在正在学习 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>

【问题讨论】:

  • 使用 &lt;%= title %&gt; 而不是 &lt;% title %&gt; 将其输出到 html,就像在 rails (.erb) 中一样。
  • 谢谢@Ravi - 打算把它放在我的例子中。这是我坚持的动态内容 - 不知道如何让它工作。
  • 好吧,我不知道这是否支持,但请检查一下,github.com/tj/ejs/issues/93
  • 再次感谢@Ravi - 也许我应该改用 Jade(个人不是粉丝) - +1 为您提供帮助 :)

标签: node.js ejs embedded-javascript


【解决方案1】:

Looks like this is now supported in EJS。它是在v2.0.1: 2015-01-02 中介绍的。新语法如下所示

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

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

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

【讨论】:

    猜你喜欢
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多