在express.js中,“app.render”和“res.render”有什么区别?

82

app.render文档:

使用回调函数渲染视图并响应渲染后的字符串。这是应用级别的res.render()的变体,其他方面行为相同。

res.render文档:

使用回调函数渲染视图并响应渲染后的字符串。当发生错误时,会在内部调用next(err)。当提供回调函数时,可能的错误和渲染后的字符串都会传递,不执行自动响应。

我该如何确定何时使用哪个方法?

3个回答

149
以下是一些不同之处:
  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

@zeMicro,缓存机制怎么样?app.render也使用它吗? - fider
如何在客户端获取标题键值?我正在使用HTML文件(ejs)。 - Mangesh Sathe

24

在需要呈现视图但不通过http发送到客户端的情况下,应使用app.render。比如说html邮件。


1
除了这两个变体,还有一个jade.renderFile,它生成的HTML不需要传递到客户端。

用法-

var jade = require('jade');

exports.getJson = getJson;

function getJson(req, res) {
    var html = jade.renderFile('views/test.jade', {some:'json'});
    res.send({message: 'i sent json'});
}

getJson()在app.js中作为路由可用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接