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}}
.
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}}
.
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');
By default, Express will look for handlebars templates in the views
folders. Let’s create it, and add our first handlebars template: home.handlebars
.
We now need to tell our /
route to use that template.
Let’s add another route for contact by creating the contact.handlebars
file.
// Contact
app.get('/contact', function (req, res) {
res.render('contact');
});
As we tell our route to render the contact
template, we need to create a contact.handlebars
file.
Since we now have two routes, we can add navigation links to go from one route to the other.
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.