Paul D. Waite
Paul D. Waite

Reputation: 98846

In Express, can I automatically include the request object as a local for all rendered templates?

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.js

...
app.get('/', function (req, res){
    res.render('home.swig', {
        "req": req
    });
});
...

home.swig

...
{% 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

Answers (1)

Mike S
Mike S

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

Related Questions