Loading dynamic data with handlebars

By: Ryan Wong at

Its very fustrating when you have to create elements on the fly using the json data you got from the server.

The javascript gets very bulky and messy.

To solve this you could use handlebars.js. Handlebars.js is a templating library to help you preload templates
that you can pass in information and use.

Steps:
1.Download handlebars.js from their site.

2.Depending on which view engine you use, you have two options:

  • if your template engine uses double curly braces for tags, you must load your handlebar template by ajax
  • if your template does not use it, you can just include it in your html file like the following:
1
2
3
4
5
6
7
<script id="some-template-tpl" type="text/handlebars">
<a class="btn blue btn-block" href="/gosomewhere"><i class="icon-eye"></i> Blah</a>
{{#if isAdmin}}
<a class="btn btn-info btn-block" href="/gosomewhereelse">
<i class="icon-eye"></i> Blah Blah</a>
{{/if}}
</script>

3.You will need to compile the template and input the data into the template.

  • loading template in using ajax

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    $.ajax({
    url: '/js/templates/some-template-tpl.js',
    cache: false,
    dataType: 'text',
    success: function(data) {
    var template = Handlebars.compile(data);
    var someDataLoadedBeforeThis = [...];
    someDataLoadedBeforeThis.map(function(oneData){
    $('#container').append(template({
    a: oneData.id,
    c: oneData.id == oneData.blah
    }));
    return false;
    });
    }, error: function(xhr, ajaxOptions, thrownError) {

    }
    });
  • loading template from script tag

    1
    2
    3
    4
    5
    6
    7
    var template  = Handlebars.compile($('#some-template-tpl').html());
    var someDataLoadedBeforeThis = [...];
    someDataLoadedBeforeThis.map(function(oneData){
    $('#container').append(template({
    a: oneData.id,
    c: oneData.id == oneData.blah
    }));

Hope this helps.