Handlebars: Templating for Javascript
JournalOn 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>'
$('#page').html(list)
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">
<ul>
<li class='title'>{{this.category}}</li>
{{#each items}}
<li>{{this.name}}</li>
{{/each}}
</ul>
</script>
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)
$('#page').html(html)
I have only created a basic example of Handlebars at work here, for more information visit handlebarsjs.com