All the examples I am seeing use the app.dynamicHelpers
to provide a method for accessing my javascript files in my view templates. But in express 3.x there is no clear way to do this. The migration docs say "use middleware". I'm relatively new to the concept of 'middleware' and don't know how to implement this.
All I would like to know is the most elegant way to include javascript files in my view templates.
Middleware is the foundation to Connect, which Express is built upon. In short, it allows you to chain together multiple handlers of an incoming HTTP request and response. The argument you provide to each app.use()
in your Express application is basically a "middleware" and is a callback with the following signature function (request, response, next)
, where next
is the next middleware callback to call in the chain. All the below are middleware (the last being an error handler which has a 4 parameter signature):
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(function(err, req, res, next){
// logic
next();
});
In terms of the move from Express 2 to 3.x, the migration is specifically:
app.dynamicHelpers(
) (use middleware +res.locals
)
So, with a contrived example, where you may have previously had a helper function in an external js
file and require
d it for use in your dynamicHelper
:
//helpers.js
exports.dynamicHelpers = {
currentUser: function(req, res) {
return req.user;
}
};
// app.js
var helpers = require('./helpers').dynamicHelpers;
app.dynamicHelpers(helpers);
With a bit of reorganization you could now do something like:
//locals.js
exports.setLocals = function(req, res, next){ //<- middleware function
res.locals.currentUser = req.user;
res.locals.otherVariable = ...;
next();
}
//app.js
var locals = require('./locals').setLocals;
...
app.use(locals);
This is a good blog with a review of middleware vs. dynamicHelpers
in pre-3.x Express, but the concepts are the same. The only difference being that res.local(name, value)
used in the article is now deprecated for res.locals.name = value
or res.locals({ name: value })