0

Trying to write some helper methods for an express 3.0 app. Here is an example to greet the user:

  app.locals.greet = function(req,res) {
    return "hey there " + req.user.name;
  }

However, req and res aren't available inside that function. How would I go about writing helpers that I can use inside my jade templates? Am I doing this wrong?

aynber
  • 22,380
  • 8
  • 50
  • 63
wesbos
  • 25,839
  • 30
  • 106
  • 143

3 Answers3

2

Have a look at my config app.js file! that should work to you as the variables will e available at that context.

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(connect.compress());
app.use(express.static(__dirname + "/public", { maxAge: 6000000 }));
app.use(express.favicon(__dirname + "/public/img/favicon.ico", { maxAge: 6000000 }));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
    secret: config.sessionSecret,
    maxAge: new Date(Date.now() + (1000 * 60 * 15)),
    store: new MongoStore({ url: config.database.connectionString })
}));
app.use(function(req, res, next){
    console.log("\n~~~~~~~~~~~~~~~~~~~~~~~{   REQUEST   }~~~~~~~~~~~~~~~~~~~~~~~".cyan);
    res.locals.config = config;
    res.locals.session = req.session;
    res.locals.utils = viewUtils;
        res.locals.greet = function(){
                //req and res are available here!
                return "hey there " + req.user.name;
        };
    next();
});
app.use(app.router);
});
Renato Gama
  • 16,431
  • 12
  • 58
  • 92
2

Here are the three parts of a simple example to show how a helper function could use req.locals:

helper function:

app.locals.greet = function(user) {
  return "hey there " + user.name;
}

view template:

h1= greet(user)

render function:

function(req, res) {
  res.render('myview', {user: req.user});
};

If you need more information on setting req.locals, see my answers here and here.

Community
  • 1
  • 1
David Weldon
  • 63,632
  • 11
  • 148
  • 146
2

You need to add a middleware function/handler that will set those values using the req/res objects before the router calls it's render method. As well, this handler needs to be defined after the information you need to know has been defined. (ie. after session middleware)

// AFTER sessions/auth/etc -- app.use(express.session(...))
app.use(function (req, res) {
    // set any locals using req/res
    res.locals.user = req.user;
    res.locals.greet = function () {
        return "hey there " + req.user.name;
    }
});
// BEFORE router -- app.use(express.router);

See the API documentation on res.locals for further information.

Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90