Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 395 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Node.js - Expressjs middleware to extend res.render

#1
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?
Reply

#2
res.locals or app.locals is for this exact purpose.

Reply

#3
[`app.locals`](

[To see links please register here]

) is likely what you're looking for:

app.locals(settings.template_defaults);

Along with [`res.locals`](

[To see links please register here]

) and [`res.render`](

[To see links please register here]

), 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('...', {
// ...
});
});
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through