nodejs / express / ejs render()同步

res.render("index.ejs", {}); 

对于简单的情况,以上情况可以。

如何使EJS返回处理的string作为函数的返回值? 让它像这样工作:

 res.send(ejs.render("index.ejs", {})); 

换句话说 – 我想嵌套/链接几个render()调用 ,而不是asynchronous的。

Express似乎并不支持这个本地,或者呢?
如果没有,那我怎样才能通过EJS直接实现呢?

如果你想知道为什么我更喜欢“坏”的方式(同步),那么我有一件事要说:caching。
无论如何,模板被caching,所以我不介意模板的第一个负载更慢(反正在几个毫秒内)。
与必须处理对render()的嵌套asynchronous调用相比,这种时间分数单延迟的代价是没有代价的。

你可以传递一个callback到res.render ,这个callbackres.render将被渲染的string调用。 这将做async这是正确的方法来解决这个问题,因为渲染可能需要一个文件读取。

 app.get('/', function(req, res){ res.render('index', { title: 'Title' }, function(err, result) { res.render('index2', {foo: 'data'}, function (err, result2) { console.log('Render result:'); console.log(result2); res.send(result2); // send rendered HTML back to client }); }); }); 

如果你不喜欢嵌套的callback,我会build议寻找一个asynchronous库,如恰当的名称async 。 你可以使用瀑布( https://github.com/caolan/async#waterfall )function来做到这一点:

 async.waterfall([ function(done) { res.render('index', {title: 'Title'}, done); }, function(result, done) { // result is the result of the first render res.render( result, {foo: 'data'}, done); } ], function (err, result) { // result is the result of the second render console.log(result); res.send(result); });