Node.js Express hbs Tutorial (Handlebars)
Most of the time when we start working on a web project, then it quickly gets complex as we write more and more code. In the beginning, if we don’t structure our code efficiently then it will most probably affect the scalability of our application in later stages.
A good starting point is to separate our website logic from the design and view part. This will make the source code a bit more clean and manageable.
If we talk about Node.js and Express application, then you might have noticed that we use JavaScript variables and logical statements directly inside our HTML files. So, in this tutorial, I’ll help you understand the power and usability of Handlebars (a JavaScript Template Engine). So let’s start with this Node.js Express Hbs tutorial with the available template engines:
Available Template Engines
First of all, let’s have a quick look at available JavaScript template engines that might be more suitable in different scenarios.
Now you have seen that there are tons of template engines that are based on JavaScript language. But, the main reason behind using Handlebars in this tutorial is that it provides a more minimalistic approach than others.
In simple words, through Handlebars, you can achieve more by just writing a few lines of code.
What is Handlebars?
Handlebars is a free and opensource JavaScript Template Engine that allows us to inject JavaScript property values directly into our HTML code. Basically, it works as a compiler, which means that it takes some input, then compiles and transforms it into a result.
In our case, we have to input the HTML and JavaScript code inside the Handlebars file. It will then automatically compile the code (fill the values) and return the actual HTML web page.
At the time of this writing, Handlebars aka hbs has received 15.2K stars on its Github repository. It has a large community of users while 150+ professional developers had contributed their code and time for the enhancement of this library.
It is designed to be the superset of popular library Mustache that is used for generating logic-less templates. To speed up the overall process, it transforms the hbs templates into JavaScript functions.
Setup a Project
Before writing any code, I assume that you have already installed Node.js and Npm on your computer. If so, we’re good to set up our Node.js, Express and Handlebars project.
At first, you need to create a folder that will contain our whole project. After that, install Express and Handlebars in it.
npm i express
npm i express-handlebars
Now we need to create some more folders that will help us arrange our Handlebars templates. I’ll name the main folder as “views” while also adding 2 sub-folders in it with the name “layouts” and “partials”.
Mostly, the templates inside “layouts” folder is used to implement a common style on all web pages of a website while on the other hand “partials” folder contains small reusable parts like header, menu, footer, etc.
For the purpose of this tutorial, let’s create a file named “home.hbs” in “views” and “main.hbs” inside the sub-folder “layouts”.
We will use “main.hbs” to store the layout of our website that can be easily applied on different web pages. Similarly, “home.hbs” refers to the actual file that contains the data of a specific web page.
In this tutorial, I’ll also apply some style to our web page using CSS. So, let’s create a “public” folder inside your project and then place a file called “styles.css” in it.
Start Writing Some Code
Create a file named “index.js” inside your project root and import the recently installed JavaScript modules in it.
Load Express module
const express = require('express');
Load Handlebars module
const handlebars = require('express-handlebars');
To create an Express application you need to initialize it using the below code.
Run Express
const app = express();
Now its time to configure the Handlebars template engine for our app.
Configure our application to utilize the Handlebars engine
app.set('view engine', 'hbs');
Settings for Handlebars
app.engine('hbs', handlebars({
layoutsDir: __dirname + '/views/layouts',
extname: 'hbs',
defaultLayout: 'main'
}));
The first line of the above code snippet is really simple and straightforward as here we are just telling Express to use Handlebars for rendering our web pages. Later on, I added some settings to define the layouts directory, file extension and default layout of Handlebars templates.
Let’s inform Express to allow the usage of static files inside our application from “public” folder. Please note that this step is very important to use static files like CSS on our website.
app.use(express.static('public'));
Now set up a route through which we can access or view our web page.
app.get('/', (req, res) => {
// Integrates the body of "home.hbs" inside the defaultLayout "main.hbs"
res.render('home');
});
At last, we just need to set a port and execute our code.
Set a port
const port = 3000;
Start our application
app.listen(port, () => console.log(`App listening to port ${port}`));
Create and Style Web Pages
We already created our template and CSS files. In this section, we have to add some code there.
Open “main.hbs” layout file and insert the below code in it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
Open “home.hbs” and enter the below code.
<h1>List of Countries</h1>
<ul>
<li class="blue_item">Australia</li>
<li class="blue_item">USA</li>
<li class="red_item">Pakistan</li>
<li class="blue_item">UK</li>
<li class="red_item">Japan</li>
</ul>
Now style the above markup language code using CSS.
li {
list-style: none;
font-size: 20px;
width: 300px;
margin: 5px;
padding: 5px;
}
.blue_item {
background-color: #0000ff;
color: #fff;
}
.red_item {
background-color: #ff0000;
}
Test our application
Write below code in project console.
node index.js
After that open the website in a browser by typing this URL.
Now that you have a complete project learn how you can deploy to Heroku under 5 minutes
Conclusion
Handlebars templating engine can have a significant impact on the growth and scalability of your project. It enables us to write better, cleaner and less code due to its minimalistic structure.
A lot of enterprise-level companies use it in their tech stack. Among them, the most noticeable are Intel, Slack, DuckDuckGo and Khan Academy. So, It’s great to have Handlebars.js listed among your professional skills.