Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Expressjs middleware to extend res.render

I'd like to know if there is a built in way to extend Express.js's res.render function because, I'd like to pass a default set of "locals" to every template that is rendered. Currently I've written a small middleware that uses underscore.js's extend function to merge the default "locals" and the ones specific for that template:

app.use(function(req, res, next){
    res.render2 = function (view, locals, fn) {
        res.render(view, _.extend(settings.template_defaults, locals), fn);
    };
    next();
});

Is there a better way to do this?

like image 833
TechplexEngineer Avatar asked Dec 22 '12 04:12

TechplexEngineer


People also ask

How does Middlewares work in Express?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

How can I get Expressjs faster?

Use a load balancer Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers.

How many Middlewares you can use in Express JS?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app. use() or app.

Why does node js need middleware?

The main purpose of the middleware is to modify the req and res objects, and then compile and execute any code that is required. It also helps to terminate the request-response session and call for the next middleware in the stack.


2 Answers

app.locals is likely what you're looking for:

app.locals(settings.template_defaults);

Along with res.locals and res.render, Express is already capable of merging the values for you:

// locals for all views in the application
app.locals(settings.template_defaults);

// middleware for common locals with request-specific values
app.use(function (req, res, next) {
    res.locals({
        // e.g. session: req.session
    });
    next();
});

// and locals specific to the route
app.get('...', function (req, res) {
    res.render('...', {
        // ...
    });
});
like image 151
Jonathan Lonowski Avatar answered Sep 19 '22 09:09

Jonathan Lonowski


res.locals or app.locals is for this exact purpose.
like image 34
chovy Avatar answered Sep 22 '22 09:09

chovy