20

Updated Express.js from version 2 to 3, and the following call to app.dynamicHelpers({..}) broke as it is no longer present in V3:

app.dynamicHelpers({

    request: function(req){
      return req
    },
    ...etc.
});

There's a migration guide which says this:

  • app.dynamicHelpers() (use middleware + res.locals)

But I'm stumped how to do that. Is there a more concrete example of how to migrate that?

Related SO post: nodejs express 3.0

Community
  • 1
  • 1
prototype
  • 7,249
  • 15
  • 60
  • 94

4 Answers4

29

I had the same problem with session.user and just fixed it by understanding that the app.use function needs to be IN the configure part, not where it was before.

Before:

app.configure();
app.dynamicHelpers({
  user: function(req, res) {
    return req.session.user;
  }
});

After:

app.configure(function(){
  //...
  app.use(function(req, res, next){
    res.locals.user = req.session.user;
    next();
  });
  //...
});

for Flash have a look at connect-flash

nooitaf
  • 1,466
  • 11
  • 18
6

The solution with 16 votes is correct but be sure to use the res.locals assignment before app.use(app.router); refer to this post https://stackoverflow.com/a/12597730/1132109

Community
  • 1
  • 1
D4tech
  • 83
  • 1
  • 4
3

Have a look at the examples folder at github. For example auth:

app.use(function(req, res, next){
  var err = req.session.error,
      msg = req.session.success;
  delete req.session.error;
  delete req.session.success;
  res.locals.message = '';
  if (err) res.locals.message = '<p class="msg error">' + err + '</p>';
  if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';
  next();
});

You can then use the variable "message" in your template.

zemirco
  • 16,171
  • 8
  • 62
  • 96
3

reponse.locals.use is a new useful feature of Express that lets you send a variable to your model that first needs to be evaluated. Say, for example, you want to send 3 variables to your view, all of which have to come after a request to a mongodb. The "old" way was to nest 3 callbacks, and when the last one returned you would render your view. locals.use makes this a heck of a lot easier as it will evaluate your functions and will render your view only when all have been evaluated.

Here's a short snippet of code on how to use them (this is coffee-script, hopefully you can convert it to javascript :D)

response.locals.use (request, response, done) ->
    myAsynchMethod (value) ->
        reponse.locals.myProperty = value
        done()

In this case, there will be a variable named myProperty you can use on your view that has it's value set to whatever myAsynchMethod gave the callback.

Jason L.
  • 2,464
  • 1
  • 23
  • 41
  • where would you use response.local.use? is it defined in the app.js or in the route hanlder(req,res)->..if so when to call the render... – coool Apr 13 '13 at 12:16