Handlebars js

Jesper bisgaard

I have recently begun using handlebars js for my various jquery mobile apps. This has been a great experience and here i will try to explain why and how i have used it. I will also include extensions and plugins which i have used to handle the development.

The challenge has been entering dynamic content into lists or as changes based on user actions, and often the html for the dynamic content would be entered as strings in the javascript. But a solution for this is using a templating system like handlebars. It allows you to define templates in <script/> tags which can then be referenced in your code when you need dynamic content.

For my projects I prefere not to have my templates in <script/> tags so I found several solutions which allowed me to make separate template files. For my projects I used sync_async_loading_handlebars which is a very simple script but it handles the task really well. Using jquery mobile i found that I got the best performance if I preloaded the templates using the T.prefetch function. This loads the template data into a cache object from where it can easily be referenced later on.

Using sync_async_loading_handlebars i then entered dynamic content by creating a data object and calling T.render, as follows:

var themeData = { 
  title: 'test', 
  src: 'data', 
  class: 'some class' 
T.render('testTemplateItem', function(t) { $('.target').append(t(themeData)); }); 

My template would then look something like this.

<div class="{{class}}">
  {{#if src}}
  <div class="image-container"><img src="{{src}}" /></div>

I also found a library of handlebars extensions which are very handy. The people behind swag have composed a library of extensions which contain most of the theming functionality you could possibly want and then some.