Node.js + Express + Handlebars.js + partial views

I know this had been asked a long time ago, but no one has shown an answer in this post. So I will do so here. To ensure everyone is on the same page, I will be verbose in my answer. I apologize in advance if it seems overly simplistic.

In your server.js file (or app.js, wherever you defined handlebars as your view engine). Depending on what you are using as your npm package, such as hbs or express-handlebars etc. it may look different, but similar to this. Note: I’m using express-handlebars in this example.

file: server.js

...
var express     = require( 'express'),
    hbs         = require( 'express-handlebars' ),
    app         = express();
...

app.engine( 'hbs', hbs( { 
  extname: 'hbs', 
  defaultLayout: 'main', 
  layoutsDir: __dirname + '/views/layouts/',
  partialsDir: __dirname + '/views/partials/'
} ) );

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

...

and your file structure should look something like this:

| /views/   
|--- /layouts/
|----- main.hbs
|--- /partials/
|----- header.hbs
|----- footer.hbs
|----- ... etc.
|--- index.hbs
| server.js

And your main.hbs file should look like this:

file: main.hbs

...
{{> header }}
...
<span> various other stuff </span>
...
{{> footer }}

To denote a partial you use this syntax: {{> partialsNames }}.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)