Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Express.js Middleware - Adding items to the response object model

Express.js Middleware - Adding items to the response object model

Problem

I'm playing around with Expressjs and am attempting to extract the page title from the default template to middleware instead of passed into the view's model each time.

Default index.jade template

h1= title

p Welcome to the #{title}

Default route from template

exports.index = function(req, res){
  res.render('index', { title: "Express" });
};

I attempted the following but get an error from Express saying title is undefined when I do this.

module.exports = function(req, res, next){
    res.title = 'Express';
    next();
}

This is obviously a trivial example but it's also something that I am trying to figure out since there will probably come a time where I want to inject things into the response's model after each route. I just cannot figure out how to do such.

Thanks

Problem courtesy of: JamesEggers

Solution

You have to use default helpers. Read the documentation. Here's a simple snippet:

app.helpers({
    title: 'Express'
});
/* Now JADE sees your variable title
   without explicitly defining it
   in every view. */

Also look at dynamic helpers in the documentation. These can be linked to req and res variables (normal helpers do not depend on request/response).

Solution courtesy of: freakish

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Express.js Middleware - Adding items to the response object model

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×