Multiple layouts with Handlebars and ExpressJS?

Jake Wilson picture Jake Wilson · May 26, 2015 · Viewed 13.7k times · Source

If I'm using Handlebars as my templating engine with Express 4, it seems like there is only the option to specify a single layout template to use for all your views:

app.engine('hbs', expressHbs({extname:'hbs', defaultLayout:'layout.hbs'}));

What if your app needs multiple layouts? What if viewA.hbs uses one layout and viewB.hbs needs a different layout?

As I'm learning nodejs, I'm coming from a PHP Laravel background where the Blade templating engine has you specify which layout to use at the top of each view file. It makes it really simple to switch between layout templates for any given view.

Answer

Ryan picture Ryan · May 26, 2015

You should be able to pass in the layout from your route/controller when you call the render method.

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

I am pretty sure jade will let you switch layouts from inside the template but I don't know if you can do that with handlebars.