Brettetete Brettetete - 2 months ago 18
Node.js Question

How do I reuse my layout with handlebars in express?

Okay I don't want to include my actual layout in every view.

So my views would look something like

layout.hbs



<html lang="en">
<head></head>
<body>
<div id="content">
{{ content }}
</div>
</body>
</html>


index.hbs



<div>my index content</div>


help.hbs



<div>my help content</div>





When I use my express routes like the following examples I just had to include my whole layout stuff in each view - which is obviously a bad idea.

express routes



app.use('/', function (req, res) {
res.render('index', {content: 'foo'});
});
app.use('/about', function (req, res) {
res.render('about', {content: 'foo'});
});


So the question is: How do I reuse my layout in handlebar views?

My idea was to compile my content additionaly like

app.use('/', function (req:express.Request, res:express.Response, next:Function) {
fs.readFile(path.join(viewPath, 'index.hbs'), function(err, text){
var template = hbs.handlebars.compile(text);
var content = template({foo: 1234});
res.render('layout', {content: content});
});
});


But I'm not sure if this is the right way.

Answer

You can use express-handlebars and give it a default layout.

var hbs = exphbs.create({
    extname:'hbs',
    layoutsDir:  '/path/to/layouts',
    defaultLayout: 'main'
});

// Initialize engine
app.engine('hbs', hbs.engine);

// Set engine
app.set('view engine', 'hbs');

Once the layout is set, you can just call res.render({content: content});

Comments