简体   繁体   English

nodejs/express/ejs render() 同步

[英]nodejs/express/ejs render() synchronous

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

The above would be fine for simple cases.以上对于简单的情况就可以了。

How do I make EJS return the processed string as the function's return value?如何让 EJS 返回处理后的字符串作为函数的返回值? Make it work like this:让它像这样工作:

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

In other words - I want to nest/chain a few render() calls , NOT asynchronously.换句话说 -我想嵌套/链接一些 render() 调用,而不是异步调用。

Express doesn't seem to support this natively, or does it? Express 似乎本身不支持这个,是吗?
And if not, then how would I achieve it directly through EJS?如果没有,那么我将如何直接通过 EJS 实现它?

If you wonder why I prefer the "bad" way (synchronous) then I got one thing to say: Cache.如果您想知道为什么我更喜欢“坏”方式(同步),那么我要说一件事:缓存。
The templates are being cached anyway, so I don't mind the first load of the template to be slower (in just a few ms anyway).无论如何,模板都会被缓存,所以我不介意模板的第一次加载速度变慢(无论如何只需几毫秒)。
This cost of single delay of a time fraction is no cost compared to having to deal with nested async calls to render().与必须处理对 render() 的嵌套异步调用相比,这种时间分数的单次延迟成本是零成本。

You can just pass a callback to res.render which will be called with the rendered string. 您可以将回调传递给res.render ,它将使用呈现的字符串进行调用。 This will be done async which is the right way to approach this since rendering may require a file read. 这将完成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
    });
  });
});

If you don't like nested callbacks, I would suggest looking at an async library like the aptly names async . 如果您不喜欢嵌套回调,我建议您查看异步库,如aptly names async You can use the waterfall ( https://github.com/caolan/async#waterfall ) function to do this: 您可以使用瀑布( https://github.com/caolan/async#waterfall )函数来执行此操作:

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);
});

Have you try ejs.renderFile?你试过 ejs.renderFile 了吗? its result is an HTML that you can send to the client.其结果是一个 HTML,您可以将其发送给客户端。

Would be something like会是这样的

res.send(await ejs.renderFile('./path/to/ejs/file.ejs', {}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM