Home > Mobile >  How to always pass 'render' parameters in Express
How to always pass 'render' parameters in Express

Time:06-02

I'm building a website where some parameters need to be passed to the frontend for every page that's loaded (ie text that's used in a navbar that is on everypage). At the moment I'm just including all the parameters in every render line but I'm wondering if there's a more efficient way to do it (in middleware for example). The two parameters below are being used in every render.

return res.render('index', {
    docTitle: i18n.__('home'),
    isLoggedIn: req.session.isLoggedIn,
})

CodePudding user response:

You could create your own render function, where you set the default values and delegate to res.render:

const customResRender = (req, res, page, params = {}) => 
  res.render(page, {
    docTitle: i18n.__('home'),
    isLoggedIn: req.session.isLoggedIn,
    ...params
  });

Then, use it instead of res.render:

app.get("/someHandler", (req, res) => {
  // ...
  customResRender(req, res, "index");
});
  • Related