JavaScript / Programmings

Getting Started With Handlebars.js – Templating Engine for JavaScript.

 

Handlebars.js is a Logic-less template engine for JavaScript. When we need an application with frequently updating view, template engine has to play big role. It keep you HTML pages simple, clean and decouples from logic based JavaScript files. Also reduce effort by reducing loops with native JavaScript.

It is also possible to precompile your templates with handlebar js. This will result in a smaller required runtime library and significant savings from not having to compile the template in the browser. This can be especially important when working with mobile devices.

Logic-less Templates

  • There should be little to no logic in your templates
  • Do not allow arbitrary JavaScript code in the template
  • You must use the small set of constructs offered by the templating language, which may include basic loops, conditionals, and partials.

Getting Start

First, We are going to start with a simple example.

  1.  Download Handlebars js from http://handlebarsjs.com
  2.  Create an html page and include handlebars js file on script tag.

In html:


<div id="hd-begin">
    <script id="hb-template" type="text/x-handlebars-template">
        <h3>{{title}}</h3>        
            <div class="test">
                {{test}}
            </div >
    </script>
</div>  

In JavaScript:


var source = $('#hb-template').html();
var template = Handlebars.compile(source);
var context = {
    title: "Handlebars Test",
    test: "It is a Logic-less Template"
};
var html = template(context);
$('#hd-begin').html(html);

It will render the view as:


<div id="hd-begin">
     <h3>Handlebars Test</h3>        
     <div class="test">
     It is a Logic-less Template
     </div>
</div>

References

  1. http://handlebarsjs.com
  2. http://tryhandlebarsjs.com

One thought on “Getting Started With Handlebars.js – Templating Engine for JavaScript.

Leave a comment