/* Usage: Set a global/default layout with: app.set('view layout', 'foo'); Set a layout per-render (overrides global layout) with: res.render('foo', { layout: 'bar' }); Or disable a layout if a global layout is set with: res.render('foo', { layout: false }); If no layout is provided using either of the above methods, then the view will be rendered as-is like normal. Inside your layout, the variable `body` holds the rendered partial/child view. Installation: Call `mpResponse();` before doing `require('express');` in your application. */ function mpResponse() { var expressResponse = require('express/lib/response'), expressResRender = expressResponse.render; expressResponse.render = function(view, options, fn) { options = options || {}; var self = this, req = this.req, app = req.app, layout, cb; // support callback function as second arg if (typeof options === 'function') fn = options, options = {}; // merge res.locals options._locals = self.locals; // default callback to respond fn = fn || function(err, str) { if (err) return req.next(err); self.send(str); }; if (typeof options.layout === 'string') layout = options.layout; else if (options.layout !== false && typeof app.get('view layout') === 'string') layout = app.get('view layout'); if (layout) { cb = function(err, str) { if (err) return req.next(err); options.body = str; expressResRender.call(self, layout, options, fn); }; } else cb = fn; // render app.render(view, options, cb); }; }