- Comments and Path expression are two advantage features for Handlebar templating.
- In this Demo, “We will see how to use comment inside a template.We will also see how a relative path expression works in a handlebar template“.
- You can check my previous post for basics of handlebar templating.
- Comments inside the templates will be ignored by the handlebar compilers.So It can not be downloaded to the browser while rendering.
- We can create comment inside a template by two ways, {{!– –}} and {{! }}.
- Using Relative path Expression,we can call other object which are not in the current context.
- The markup below shows the use of comment and relative path(../course) expression to access the course name while iterating over the student object inside the each loop .
<!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">
<ul>
{{! comment:built in each helper for iterating object}}
{{#each students}}
{{!--comment:displaying name and using relative path to access the course --}}
<li>{{ this.name }} is enrolled in {{ ../course}}</li>
{{/each}}
</ul>
</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>
- The JavaScript file which have the code for compilation of template are 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 demo student JSON data we have used is as below,
{
"course":"M.Tech Computer",
"students": [
{
"name": "sandeep",
"mark": 35,
"subject": "Geography"
},
{
"name": "sangeeta",
"mark": 24,
"subject": "English"
},
{
"name": "Jack",
"mark": 55,
"subject": "English"
}
]}
- The output and firebug inspection in browser looks as below,