Handlebars js

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:

  1. var themeData = {
  2.   title: 'test',
  3.   src: 'data',
  4.   class: 'some class'
  5. };
  6. T.render('testTemplateItem', function(t) {
  7.   $('.target').append(t(themeData));
  8. });

My template would then look something like this.

  1. <div class="{{class}}">
  2.   {{#if src}}
  3.   <div class="image-container"><img src="{{src}}" /></div>
  4.   {{/if}}
  5.   <h2>{{title}}</h2>
  6. </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.