Created
August 9, 2010 23:06
-
-
Save weaver/516298 to your computer and use it in GitHub Desktop.
Express middleware for adding template bindings #nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is rudimentary view-level middleware for Express. When | |
// ServerResponse.render() is called, any middleware methods are | |
// invoked in the order they were registered. They are passed the | |
// request, response, and local template bindings. | |
// | |
// For example: | |
// | |
// var connect = require('connect'), | |
// app = require('express').createServer(); | |
// | |
// app.configure(function() { | |
// app.use(connect.cookieDecoder()); | |
// app.use(connect.session()); | |
// app.use(viewMiddleware(accountDetails)); | |
// app.use(app.router); | |
// }); | |
// | |
// function accountDetails(req, res, locals) { | |
// locals.account = req.session.accountId; | |
// } | |
// | |
var VIEW_MIDDLEWARE = []; | |
function viewMiddleware(fn) { | |
fn && VIEW_MIDDLEWARE.push(fn); | |
return function viewMiddleware(req, res, next) { | |
res.request = req; | |
next(); | |
}; | |
} | |
function addBindings(req, res, locals) { | |
VIEW_MIDDLEWARE.forEach(function(fn) { | |
fn(req, res, locals); | |
}); | |
return locals; | |
} | |
var origRender = http.ServerResponse.prototype.render; | |
http.ServerResponse.prototype.render = function render(name, options, fn) { | |
options = options || {}; | |
options.locals = addBindings(this.request, this, options.locals || {}); | |
return origRender.call(this, name, options, fn); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment