Use Handlebars and Express in Node.js

Node.js is an excellent server side platform that makes it really easy to write and deploy sites. In this post, I will demonstrate how to use Node.js in combination of Express and Handlebars to create an example registration form. You can view a tutorial one how to create a project at this link or use your IDE.

Views

We need to define a couple of web pages for the view. The first page is a master template that is used when serving every page in the site.

layout.hbs

Layout_hbs

There are a couple of interesting aspects about the layout.hbs code fragment. For one thing, it provides us with a common place to define our site level css and javascript. In this example, both jQuery and Bootstrap are added in this file and are therefore included in every other page.

The other aspect is the {{{body}}}. The layout.hbs code does not have its own body. Instead, it use a placeholder {{{body}}} that represents what will utlimately become the body of each html page. Our next two pages only define the body portion of the page and they are inserted into the html page at the {{{body}}}.

index.hbs

The index.hbs is one of two files that are inserted at the {{{body}}} portion of the labyout.hbs file. This file provides the user with an example registration form.

index_hbs

In all truthfulness, there isn’t anything special about this page whatsoever. This page is literally a regular html form with some bootstrap css to make it look presentable. The magic happens on the backend with the index.js file.

index.js

This file contains the code that handles both HTTP GET and HTTP Post requests.

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Node Tutorial' });
});

router.post('/', function(req, res){
//Grab the request body
var body = req.body;

var res_body = {
first_name: body.first_name,
last_name: body.last_name,
email: body.email
};

res.render('welcome', res_body);
});

module.exports = router;

This script work by creating two variables. First an express variable followed by a router variable. The router is the object that does the work of handling HTTP requests. The first function is a router.get(‘/’, function(…){…}). That function handles all HTTP GET requests to our index page which is mapped to the root of the site “/”. The call back function takes three parameters: req, res, and next. Next is unused in this example but req stands for Request and contains the request body the browser sent back to the server. The res stands for Response and represents the response the server sends back to the browser.

The function for our GET request has only one line of code. res.render('index', {title: 'Node Tutorial' }). Although it doesn’t seem like much, that single line of code packs a massive punch. For one thing, it is tell the server to combine the layout.hbs and index.hbs into one html document by inserting index.hbs at the {{{body}}} placeholder in layout. It’s also telling the template engine to insert the phrase ‘Node Tutorial’ at the {{title}} placeholder found in layout.hbs. When these operations are complete, the browser gets an html file that resembles the screen shot below.

homepage

The next function is the router.post('/', function(...){...}). This function handles http post requests for the homepage. On the first line of this function, we store the request body inside of a body variable. Each property on the body, first_name, last_name, email, pw, pw_confirm all represent our text boxes in index.hbm as specified by the name attribute on each of those input fields. So when the user enters ‘Bob’ in the box labeled as First Name on our form, the body.first_name gets set to the String ‘Bob’. This is true for each field on the form.

All we are doing in this particular example is gathering the first_name, last_name, and email fields from the request body and storing them in an object res_body. The last line of code res.render('welcome', res_body); tells the server to redirect to the welcome.hbm page and pass the res_body variable to the template engine. This will allow the template engine to access the values stored in res_body when it renders the the welcome page.

welcome.hbs

The final page of this project is the welcome.hbm page. This page is incredibly similar to the index.hbs page in that it gets inserted into layout.hbs at the {{{body}}} variable. Here is the code for welcome.hbm

welcome_hbs.png

This page defines three placeholders: {{first_name}}, {{last_name}}, and {{email}}. All of these place holders map to the properties in the res_body variable that we sent back to the view in index.js. When the template engine sees the res_body variable, it knows to insert res_body.first_name at {{first_name}}, res_body.last_name at {{last_name}}, and res_body.email at {{email}}. Below is a screenshot of the result.

Conclusion

Node.js make it really easy to create an MVC style site. Developers need to leverage the router variable and map html end points to various HTTP request and then respond as needed. Information can be easily sent back to the view using JavaScript objects where the values can get inserted into Handlebars templates.

You can get the code for this tutorial at my Github page.
Visit the video tutorial at https://youtu.be/rEdQ6fvSNOk

Advertisements

5 thoughts on “Use Handlebars and Express in Node.js”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s