【问题标题】:Node.js: use underscore along with ejs to render htmlNode.js:使用下划线和 ejs 来呈现 html
【发布时间】:2017-03-18 16:29:35
【问题描述】:

我目前正在使用 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 设置中的某个地方?)

【问题讨论】:

    标签: javascript node.js express underscore.js ejs


    【解决方案1】:

    您可以将_ 绑定到app.locals

    设置后,app.locals 属性的值将始终保持不变 与 res.locals 属性相比,应用程序的生命周期 仅在请求的生命周期内有效。

    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

    app.localsreq.locals 上查看the documentation

    我只是在名字 'john' 和 'marry' 周围加了引号

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多