Brettetete Brettetete - 11 months ago 78
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


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


<div>my index content</div>


<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 Source

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

var hbs = exphbs.create({
    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});