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.
- Download Handlebars js from http://handlebarsjs.com
- 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>
- The Js fiddle of above example is here.
- See another example here in Js fiddle.
References
A good article about the absolute fastest templating framework for JavaScript. With Handlebars, you can separate the generation of HTML from the rest of your JavaScript and write cleaner code.
Here is one starter tips of Handlebars JS:
http://www.namasteui.com/getting-started-with-handlebars-js/
Hope this helps.
—
Regards,
Chris
Namaste UI