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

NodeJS/Express: implicitly push data from custom middleware into render call

NodeJS/Express: implicitly push data from custom middleware into render call

Problem

I'm using NodeJS/Express3.

I have some Custom Middleware which retrieves some data from a database, based on cookie and URL.

I want to have access to this data in the base template (used for all pages).

I can do this explicitly by attaching the data to the req, and then using res.render('template', {foo: req.foo, ...page specific data...});

I want to make this implicit, so as I add (or remove) Custom middleware I don't have to change every render call.

  • Is there a way of making data from custom middleware available to render without having to add it to req and explicitly pass it through every single render request.

I'm using LinkedIn's version of dust.js templates, but I think the question is template engine agnostic.

Problem courtesy of: chrisdew

Solution

I think the answer may lie in res.locals. http://expressjs.com/api.html#res.locals

Solution courtesy of: chrisdew

Discussion

View additional discussion.



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

Share the post

NodeJS/Express: implicitly push data from custom middleware into render call

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×