javascript - Node.js:使用下划线和 ejs 来呈现 html

标签 javascript node.js express underscore.js ejs

我目前正在使用 EJS 模板引擎来呈现我的 HTML 页面,但我想添加下划线以简化预处理。现在我这样做并且有效:

var _ = require("underscore");

app.get('/', function(req, res){
    var data = {};
    data.people = [{ name: "john" }, { name: "marry" }];
    data._ = _; // inject underscore.js
    res.render('index', data);
});

现在渲染我有权访问下划线的 HTML:

<% _.each(people, function(person){ %>
    <div><%= person.name %></div>
<% }); %>

但是,我必须为每条路线注入(inject)下划线,有没有办法始终注入(inject)下划线? (也许在 app.engine 设置的某个地方?)

最佳答案

您可以将 _ 绑定(bind)到 app.locals

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

app.locals._ = _;

app.get('/', function(req, res){
    var data = {};
    data.people = [{ name: 'john' }, { name: 'marry' }];
    res.render('index', data);
});

在你看来:

<% _.each(people, function(person){ %>
    <div><%= person.name %></div>
<% }); %>

另一个 SO 用户给出了一个很好的答案:Access req and res inside of app.locals

参见 the documentation app.localsreq.locals

我只是在名字“john”和“marry”周围添加了引号

关于javascript - Node.js:使用下划线和 ejs 来呈现 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29999972/

相关文章:

javascript - 使用 mongodb 操作运行 for-in 循环

javascript - 是否可以通过 JavaScript 捕获 Silverlight 控件的鼠标事件?

javascript - 为什么在用 document.write() 编写时拆分 &lt;script&gt; 标签?

javascript - Visual Studio 2013-Javascript

node.js - 使用 Mocha 进行 Express 测试失败

javascript - 通知服务器有关图像上传的 Azure Blob

javascript - 无法将用户存储在 Express.js session 中

javascript - 根据特定键将对象数组转换为深层嵌套对象

javascript - 如何在 imap-simple 中检索 "sent"邮箱

javascript - 如何允许来源中的所有端口