Lesson 2: Handlebars Templates

1 Import handlebars

We first need to import a new dependency: Handlebars.

Handlebars templates are basically simple HTML, in which we can inject variables. The syntax is {{variable}}.

var exphbs = require('express-handlebars');
Copy to clipboardapp.js

2 Set up handlebars

We then need to tell our app to actually use handlebars as our template engine.

// Register '.handlebars' extension with exphbs
app.engine('handlebars', exphbs());
// Set our default template engine to "handlebars"
app.set('view engine', 'handlebars');
Copy to clipboardapp.js

3 Create handlebars files

By default, Express will look for handlebars templates in the views folders. Let’s create it, and add our first handlebars template: home.handlebars.

<h1>Home Page</h1>
Copy to clipboardviews/home.handlebars

4 Use handlebars template

We now need to tell our / route to use that template.

app.get('/', function (req, res) {
  res.render('home');
});
Copy to clipboardapp.js

5 Create a second route

Let’s add another route for contact by creating the contact.handlebars file.

// Contact
app.get('/contact', function (req, res) {
  res.render('contact');
});
Copy to clipboardapp.js

6 Add the contact template

As we tell our route to render the contact template, we need to create a contact.handlebars file.

<h1>Contact Page</h1>
Copy to clipboardcontact.handlebars

Since we now have two routes, we can add navigation links to go from one route to the other.

<nav>
  <a href="/">Home</a>
  <a href="/contact">Contact</a>
</nav>
Copy to clipboardapp.js

8 Use a header partial

Since we have the exact same HTML snippet in both templates, let’s use a partial to avoid repeating ourselves.

Create a new folder in views/partials in which we create a new file called header.handlebars.

We can now reference that partial in the templates.

{{> header}}
Copy to clipboardheader.handlebars