Using Handlebars with Node.js
Handlebars is a simple templating language.
It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions. After a lot of consideration, I chose Handlebars as the templating engine for my portfolio. It’s minimal, powerful and blends well with express.
<p>{{firstname}} {{lastname}}</p>
Web templating does something very similar. It uses a templating processor that takes data from a source of information, typically a database and a template, a generic HTML file with some kind of parameters inside. The processor then merges the data and template to generate a bunch of static web pages or dynamically generates HTML on the fly.
Node.js
Node.js has just revolutionized the world of web development. During its introduction, it shocked the whole world. Today, Node.js is considered by many to be the coolest thing. Node.js is a different way of doing web development. Rather than writing an application and using a web server to transfer your code to a browser, the application and the web server are one and the same thing.
Popular contenders
Node.js w/ express supports a lot of HTML templating engines. Some popular choices are:
- Pug
- Mustache
- Handlebars
- Marko
- EJS
Installation
Install using npm:
$ npm install express-handlebars
Usage
This view engine uses sensible defaults that leverage the “Express-way” of structuring an app’s views. This makes it trivial to use in basic apps:
Basic Usage
Directory Structure:
app.js:
Creates a super simple Express app which shows the basic way to register a Handlebars view engine using this package.
views/layouts/layout.handlebars:
Let’s test this out by typing the command below on the command prompt:
$ npm run start
If everything works fine we should be able to see the message “App listening to port 3000” on the console and if we open this URL “ http://localhost:3000/” in the browser we should be able to see a nice shiny “Hello World !” on the page.
Templates
In the views/ folder, create a , index.handlebars, and error.handlebars with the following content:
Summary
In this article, we talked about using templates in web development. Then, we zoomed in on using Node.js and Express, and introduced Handlebars.js. Handlebars.js is cool, as it lets you separate logic from layout and you can use it server-side (which is where we focused on), as well as client-side. Moreover, you will still be able to use HTML for your views and layouts, unlike with other templating processors.