Skip to content

Instantly share code, notes, and snippets.

@weaver
Created August 9, 2010 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaver/516298 to your computer and use it in GitHub Desktop.
Save weaver/516298 to your computer and use it in GitHub Desktop.
Express middleware for adding template bindings #nodejs
// 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