m81m-q
Last Updated: February 25, 2016
·
3.651K
· ju

Overriding Express.js res.render

This is useful for doing any pre or post processing on the final result of your render.

This should be placed high in the middleware array, to insure all calls to res.render are handled by the same function.

https://gist.github.com/mrlannigan/5051687

/**
 * Override res.render to do any pre/post processing
 */
app.use(function(req, res, next) {
  var render = res.render;
  res.render = function(view, options, fn) {
    var self = this,
      options = options || {},
      req = this.req,
      app = req.app,
      defaultFn;

    if ('function' == typeof options) {
      fn = options, options = {};
    }

    defaultFn = function(err, str){
      if (err) return req.next(err);
      self.send(str);
    };

    if ('function' != typeof fn) {
      fn = defaultFn;
    }

    render.call(self, view, options, function(err, str) {
      // do whatever post processing you want
      fn(err, str);
    });
  };
  next();
});

1 Response
Add your response

16160

Does it override render on every request ?

over 1 year ago ·