Re: Locals - Every Request

82 views
Skip to first unread message

greelgorke

unread,
Oct 24, 2012, 3:52:56 AM10/24/12
to expre...@googlegroups.com
with res.set you set Header fields.

what you want is res.locals or app.locals


greets


Am Dienstag, 23. Oktober 2012 23:14:17 UTC+2 schrieb Jeff Sheldon:
Sorry if this is a stupid question, still learning.

But is there a way to set a local on every request?  For variables in the Layouts (in the case of jade)

I'm trying:
app.use(function (req, res, next) {
    res.set({ someValue: "1" });
    next();
});

But I still get a reference error within the view.  Am I just doing this wrong? Or is this not possible?

-Jeff

Jeff Sheldon

unread,
Oct 24, 2012, 9:21:08 AM10/24/12
to expre...@googlegroups.com
I thought I'd tried that previously.

So towards the top I have:
app.use(function (req, res, next) {
    res.locals.currentTime = new Date();
    next();
});

app.get('/', routes.index);

Then in routes.index I have:
exports.index = function (req, res) {
    res.render('index');
/*
    I *did* have the following, which I thought was causing the problem.
    res.render('index', { title: "Welcome" });
*/
};

And in my view I simply have
=currentTime

But I still get the following reference error that currentTime is undefined:
currentTime is not defined
at eval (eval at (.....\node_modules\jade\lib\jade.js:176:8))
at Object.exports.compile (.....\node_modules\jade\lib\jade.js:181:12)
at ServerResponse.res._render (....\node_modules\express\lib\view.js:425:23)
at ServerResponse.res.render (....\node_modules\express\lib\view.js:318:17)
at exports.index (....\routes\index.js:7:9)
at callbacks (....\node_modules\express\lib\router\index.js:272:11)
at param (....\node_modules\express\lib\router\index.js:246:11)
at pass (....\node_modules\express\lib\router\index.js:253:5)
at Router._dispatch (....\node_modules\express\lib\router\index.js:280:5)
at Object.middleware [as handle] (....\node_modules\express\lib\router\index.js:45:10)


I appreciate the help.
-Jeff

Jeff Sheldon

unread,
Oct 24, 2012, 11:38:51 AM10/24/12
to expre...@googlegroups.com
Actually, I got it to work by doing this:

app.use(function (req, res, next) {
    res._locals = { 
        currentTime: new Date()
        };
    next();
});

Is that a completely wrong way to handle this?
Reply all
Reply to author
Forward
0 new messages