Handlebars: Templating for Javascript


On shared hosting environments Wordpress can see poor performance when it comes to page loading times. Here are a few easy plugins you can install to help speed up your loads times and improvement engagement with your users

A common element when developing a website or application using JavaScript is the need to manipulate the document's HTML, such as displaying a custom notification message, or the results of an AJAX request on the current page.

var list = '<ul>'

for (i = 0; i < items; i++) {
  list += '<li>' + items[i].title + '</li>'

list += '</ul>'

The code example above shows one technique of accomplishing this task, where a string is built up, and then injected into the DOM. This can result in messy and sometimes hard to read code, when the task at hand has a complex HTML structure and/or uses several variables and conditions.

An alternative technique to solve this problem is a project in the name of Handlebars.

Handlebars offers a templating system to help build and use templates for your website or application. By providing Handlebars with an array of data, it will run through a template, injecting the variable data where instructed.

The first step in using Handlebars is to create a template:

<script id="template-book-listings" type="text/x-handlebars-template">
    <li class='title'>{{this.category}}</li>
    {{#each items}}

The {{each}} and {{//each}} represent the opening and closing of a loop, where items is our data.

From within the loop, item's can be accessed using {{this}}. A template can then be used anywhere within your scripts using the following code:

var context = {
  category: 'Adventure',
  items: [
    { name: 'Moby Dick', url: 'moby-dick.html' },
    { name: 'Robinson Crusoe', url: 'robinson-crusoe.html' },
    { name: 'Treasure Island', url: 'treasure-island.html' }

var source = $('#template-book-listings').html(),
  tmpl = Handlebars.compile(source),
  html = tmpl(context)

I have only created a basic example of Handlebars at work here, for more information visit handlebarsjs.com