最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js: use underscore along with ejs to render html - Stack Overflow

programmeradmin0浏览0评论

I'm currently using EJS templating engine to render my HTML pages, but I want to add underscore to simplify the pre-processing. Right now I do this and it works:

var _ = require("underscore");

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

Now to render the HTML I have access to underscore:

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

However, I have to inject underscore for every route, is there a way to always inject underscore? (maybe somewhere in app.engine setting ?)

I'm currently using EJS templating engine to render my HTML pages, but I want to add underscore to simplify the pre-processing. Right now I do this and it works:

var _ = require("underscore");

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

Now to render the HTML I have access to underscore:

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

However, I have to inject underscore for every route, is there a way to always inject underscore? (maybe somewhere in app.engine setting ?)

Share Improve this question edited May 2, 2015 at 8:40 Maria asked May 2, 2015 at 8:13 MariaMaria 3,5357 gold badges35 silver badges49 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

You could bind _ to 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);
});

In your view:

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

There is a great answer from another SO user: Access req and res inside of app.locals

See the documentation on app.locals vs. req.locals

I just added quotes around the names 'john' and 'marry'

发布评论

评论列表(0)

  1. 暂无评论