After I was able to examine the Express 3 API Reference, I discovered what I was looking for. In particular, the entries for app.locals and then a little further on res.locals provided the answers I needed.
I myself discovered that the app.locals function takes an object and saves all its properties in the form of global variables app.locals with the application. These global variables are passed as local variables for each view. The res.locals function, however, is bound to the request, and thus the local response variables are only available for the views displayed during this particular request / response.
So for my case, in my app.js application app.js I added:
app.locals({ site: { title: 'ExpressBootstrapEJS', description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.' }, author: { name: 'Cory Gross', contact: 'CoryG89@gmail.com' } });
Then all these variables are available in my views as site.title , site.description , author.name , author.contact .
I could also define local variables for each response to the request with res.locals or simply pass variables, such as the page title, as options parameters in the render call.
EDIT: This method will not allow you to use these locals in your middleware. I actually came across this, as Pickels suggests in the comment below. In this case, you will need to create an intermediate function as such in its alternative (and evaluated) answer. The intermediate res.locals function will have to add them to res.locals for each response, and then call next . This middleware function should be placed on top of any other middleware that these locals should use.
EDIT: Another difference between declaring locals through app.locals and res.locals is that with app.locals variables are set once and stored throughout the application. When you install locals with res.locals in your middleware, they are installed every time you receive a request. Basically, you prefer to set global variables through app.locals if the value is independent of the request req variable passed to the middleware. If the value does not change, then it will be more efficient to set it only once in app.locals .
Cory Gross May 11 '13 at 22:14 2013-05-11 22:14
source share