Search code examples
node.jsexpresshandlebars.js

Render 2 templates at the same time on Node/Express


I come from the PHP scenario, so this may be a wrong question. I serve a page (templates with Handlebars) to client this way:

router.get('/', function(req, res) {
  res.render('home');
});

and it works, but what if I need to divide my template in some different parts (so I'm able to reuse one of this in many different way)? For example, I have a template for header and one for footer.

Something like this:

router.get('/', function(req, res) {
  res.render('header');
  res.render('content');
  res.render('footer');
});

How can I achieve this? Thanks.


Solution

  • Assuming you are using handlebars template rendering service, you can use partials.

    http://handlebarsjs.com/partials.html

    Code example: https://github.com/donpark/hbs/blob/master/examples/partial/views/index.hbs

    The basic high level call stack follows like this:

    res.render('page') ---> parses N of partials (recursively) --> html out