Reputation: 98846
I’ve just started learning Express. I’m finding that in my templates, I often want to use properties of the request object from my route handler. For example:
...
app.get('/', function (req, res){
res.render('home.swig', {
"req": req
});
});
...
...
{% if req.user %}
<p>You’re logged in!</p>
{% else %}
<p>You’re not logged in.</p>
<p><a href="/login">Log in here</a></p>
{% endif %}
Is there any way I can automatically include the request object as a local in all my res.render
calls, instead of specifying it explicitly in each one?
Upvotes: 0
Views: 228
Reputation: 42325
You can add a small piece of middleware to do this. It would look something like:
app.use(function(req, res, next) {
res.locals.req = req;
next();
});
Upvotes: 4