- HandleBar provides some built-in helpers in the shape of Block Level Expression.
- Some of the useful one are {{#each}}, {{#if}},{{#unless}} and {{#with}}.
- In this Demo "We will see how to use these built-in helpers for templating the JSON Data".
- Using {{#each }} we have iterated the student JSON object array and the hobbies in string array.
- {{#if }} statement is for checking Truth logic.{{#unless}} is the reverse of the {{#if }} logic.
- The HTML markup for testing the template scripts are as below,
<!DOCTYPE html>
<html>
<head>
<title>HandleBar Features (comments, path)</title>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<body>
<div id="my-container">
</div>
<script id="student-template" type="text/x-handlebars-template">
{{! comment:built in each helper for iterating object}}
{{#each students}}
<ul>
{{!--comment:displaying name and using relative path to access the course --}}
<li>{{ this.name }} is enrolled in {{ ../course}}</li>
{{#if this.mark}}
<li>Marks secured {{ this.mark }} and PASSED</li>
{{else}}
<li>--No Marks Found--</li>
{{/if}}
{{#unless this.address}}
<li>No Address Found</li>
{{else}}
<li>Address Found: {{this.address}}</li>
{{/unless}}
<li class="hobbies">
{{#each hobbies}}
{{@index}}<span> {{this}} </span>
{{! comment:For Empty hobbies list show the below message.}}
{{else}}
<span>No Hobbies found.</span>
{{/each}}
</li>
{{#with parent}}
<li>Father: {{ father }} , Mother:{{ mother }}</li>
{{/with}}
</ul>
{{/each}}
</script>
<!--Handlebar templates end-->
<script src="lib/jquery-1.10.2.min.js"></script>
<script src="lib/handlebars.js"></script>
<script src="js/my-script.js"></script>
</body>
</html>
- Below Static JSON student Data is used for the demo purpose.
{
"course":"M.Tech Computer",
"students": [
{
"name": "sandeep",
"mark": 35,
"subject": "Geography",
"parent":{"father":"Dilip Patel", "mother":"Sanjukta Patel"},
"hobbies": ["cricket" , "football"]
},
{
"name": "sangeeta",
"subject": "English",
"address":"Chennai,India",
"parent":{"father":"Dillip Patel", "mother":"Sanjukta Patel"},
"hobbies": []
},
{
"name": "Jack",
"mark": 55,
"subject": "English",
"parent":{"father":"Mr. ABCD EFGH", "mother":"Mrs. XYZA BCDE"},
"hobbies": ["tennis" , "football"]
}
]
}
- The JavaScript code for compiling Handlebar Template and using it is as below
/**
* Created by saan on 10/11/13.
*/
var STUDENT_METHOD ={
handlerData:function(resJSON){
var templateSource = $("#student-template").html(),
template = Handlebars.compile(templateSource),
studentHTML = template(resJSON);
$('#my-container').html(studentHTML);
},
loadStudentData : function(){
$.ajax({
url:"http://localhost:63342/HandleBarPartialDemo/data/studentData.json",
method:'get',
success:this.handlerData
})
}
};
$(document).ready(function(){
STUDENT_METHOD.loadStudentData();
});
- The firebug inspection code is as below,
- The output looks as below in the browser:-



