Node.js: 使用下划线和 ejs 渲染 html

Node.js: use underscore along with ejs to render html

我目前正在使用 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>
<% }); %>

但是,我必须为每个路由注入下划线,有没有办法总是注入下划线? (也许在 app.engine 设置中的某处?)

您可以将 _ 绑定到 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'

周围添加了引号