我目前正在使用 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.locals
与 req.locals
我只是在名字“john”和“marry”周围添加了引号
关于javascript - Node.js:使用下划线和 ejs 来呈现 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29999972/