Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple layouts with Handlebars and ExpressJS?

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.

like image 812
Jake Wilson Avatar asked May 26 '15 19:05

Jake Wilson


2 Answers

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.

like image 167
Ryan Avatar answered Oct 25 '22 22:10

Ryan


If you use express-hbs, you can specify a layout in the template with a comment like:

{{!< layout}}

Alternatively, you can try exphbs. It also supports layout comments and multiple layouts can be nested. (Disclaimer: I wrote it.)

like image 4
gnowoel Avatar answered Oct 25 '22 22:10

gnowoel