Simple Handlebars and Express Example

There are many different semantic templating systems out there and one such system is Handlebar.js. In this article we are going to build a very simple Express server that...

a year ago

Latest Post Automatic Offline Backup With a Raspberry Pi by Tyler Moon

There are many different semantic templating systems out there and one such system is Handlebar.js. In this article we are going to build a very simple Express server that uses Handlebar.js to insert JavaScript variables into HTML templates.

Prerequisites

Setup

To start with create a new directory by using the mkdir command in a terminal

mkdir handlebars_example
cd handlebars_example

Next initialize a package.json file to track out NPM dependencies, install the needed packages, and create a blank JavaScript file.

npm init # Just take all the defaults
npm i express handlebars --save
touch hbexample.js

Express and Handlebar Coding

Add the following code to the hbexample.js file

/****
 hbexample.js
 A simple express server that renders a handlebar template
****/

// Load Node.js Packages
const handlebars = require('handlebars');
const express = require('express');
const fs = require('fs');

// Setup Express server
const port = process.env.PORT || 3000
const app = express()

// Example data set to populate template with
var data = {
        title: 'practical node.js',
        body: 'This is an example of rendering a handlebar template!',
        twitter: '@byteunits',
        tags: ['express', 'node', 'javascript']
}

// Handlebars template (NOTE: This typically would be in a separate .html file)
var source = `
<div class="header">
  <h1>{{custom_title title}}</h1>
</div>
<div class="body">
  <p>{{body}}</p>
</div>
<div class="footer">
  <div><a href="http://twitter.com/{{author.twitter}}">{{author.name}}</a></div>
  <ul>
    {{#each tags}}
      <li>{{this}}</li>
    {{/each}}
  <ul>
</div>
`

// Setup a custom handlebar helper that properly capitalizes a title
handlebars.registerHelper('custom_title', function(title){
        var words = title.split(' ');
        for (var i = 0; i < words.length; i++) {
                if (words[i].length > 4) {
                        words[i] = words[i][0].toUpperCase() + words[i].substr(1);
                }
        }
        title = words.join(' ');
        return title;
})

var template = handlebars.compile(source);
var html = template(data);
console.log(html)

app.get('/', (req, res) => {
        res.send(html);
        res.end();
});

app.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready On Server http://localhost:${port}`)
});

This code will startup a basic Express server on localhost:3000 that the root path / will return a Handlebar template with some JavaScript values inserted into it! Of especial note is the {{#each tags}} line. This will repeat anything in the block for each element in the tags array. The for each block is one of the useful features that templates allows you do use.

Launch Server

Now its time to launch our Express server and see our Handlebars template in action.

node hbexample.js

And now navigate to localhost:3000 and you should see something like the following:

Handlebars template in action

Notice how the {{}} syntax has been replaced with the values of the JavaScript variables!

Summary

In this very brief example of how to render a Handlebars template using Express and Node.js. Checkout the handlebars GitHub for more detailed documentation.

Tyler Moon

Published a year ago

Comments?

Leave us your opinion.