What's the difference between “app.render” and “res.render” in express.js?
Render a view with a callback responding with the rendered string. This is the app-level variant of
res.render() , and otherwise behaves the same way.
Render a view with a callback responding with the rendered string. When an error occurs
next(err) is invoked internally. When a callback is provided both the possible error and rendered string are passed, and no automated response is performed.
我该如何确定何时使用哪个?
以下是一些区别:
您可以在根级别调用
看下面的例子。
-
app.render 1
2
3
4
5
6
7
8app.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>res vs app render<link rel="stylesheet" href="/stylesheets/style.css"></head><body>res vs app render<p>
Welcome to res vs app render
</p></body></html> -
res.render ,不带第三个参数1
2
3
4
5
6app.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 具有第三个参数1
2
3
4
5
6
7
8
9app.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
您可以使用
例如在外部路线中:
1 2 3 4 5 6 7 | var routes = require('routes'); app.get('/mail', function(req, res) { // app object is available -> app.render }) app.get('/sendmail', routes.sendmail); |
1 2 3 | exports.sendmail = function(req, res) { // can't use app.render -> therefore res.render } |
在需要渲染视图但不通过http将其发送给客户端的情况下,请使用
与这两个变体一起,还有
用法-
1 2 3 4 5 6 7 8 | 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'}); } |