Thursday, 12 June 2014

HTML templating with Handlebars js

I was working on a small HTML project where small amount of data needed to be updated frequently. The updates could have been updated manually, but this was too much hassle as the updates were so small. To solve this issue I used a Javascript library called Handlebars. Handlebars is a templating library that loads JSON data with the template design of your choice. This is a simple working example of Handlebars with external JSON data loaded with jquery.


The "jsonCallBack" or JSONP is used to load data from different domains without any cross domain issues. This can be removed if you are loading data from the same domain.


            "name": "Mr A"
            "image": "images/mra.jpg"
            "link": ""
            "name": "Mrs B"
            "image": "images/mrsb.jpg"
            "link": ""
            "name": "Miss C"
            "image": "images/missc.jpg"
            "link": ""



The "{{ }}" (double curly braces) indicate where we want Handlebars to generate the code for us. The Handlebars template uses the MIME type text/x-handlebars-template rather than text/javascript to prevent the browser from running the Handlebars code.

<!doctype html>
    <meta charset="UTF-8">
    <title>Mustache JS Example</title>

    <script src="js/handlebars.js"></script>
    <script id="HJ-Template" type="text/x-handlebars-template">
   {{#each example}}
        <div class="example">
            <div class="example-image"><img src={{image}}></div>
            <p class="example-text">{{name}}</p>
            <a href={{link}}>Click link</a>

    <script src="js/jquery.js"></script>
    <script src="js/main.js"></script>



This loads the example.json file with jQuery and uses the Handlers.compile() method to compile the template in Javascript. The results are added to the body of the HTML.

        url: example.json,
        dataType: 'jsonp',
        jsonpCallback: 'jsonCallback',
        success: function (data) {   

            var source = $('#HJ-Template').html(),
            template = Handlebars.compile(source),
            html = template(data.example);




  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP