Handlebars is a JavaScript templating engine that extends mustache (a logic-less templating engine) functionalities by adding a minimal logic.
It allows developer to:
- compile the template
- use :
o a minimal logic ( #if ,#unless,#with,#list,#each)
o helpers ( invoke JavaScript function {{ function_name arg1 arg2 …}}
o {{this}}
o Handelbars.SAfeString()
How to use HandelBar: a basic example
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.rc.1/handlebars.min.js"></script>
- Write your template
<script id="myTemplate" type="text/x-handlebars-template">
<h1>{{article }}</h1>
</script>
- Call your template by using JavaScript
- Call your template by using JavaScript
o Compile your template
var template = Handlebars.compile($("#myTemplate").html());
o Define a context
var conext = {article: "Test"} ;
o Set the value of “inner Html” of a div ( for example) by the html rendered value from the template
$("#placeholder").html (template (conext));
<!DOCTYPE html>
<html>
<head>
<title>Handlebars.js example</title>
</head>
<body>
<div id="placeholder">
This will get replaced by handlebars.js</div>
<script type="text/javascript" src="Js/handlebars.min.js"></script>
<script type="text/javascript" src="Js/jquery-1.11.1.min.js"></script>
<script id="myTemplate" type="text/x-handlebars-template">
<h1>{{article }}</h1>
</script>
<script type="text/javascript">
var template = Handlebars.compile($("#myTemplate").html());
var conext = {
article: "Test",
};
$("#placeholder").html(template(conext));
</script>
</body>
</html>
<html>
<head>
<title>Handlebars.js example</title>
</head>
<body>
<div id="placeholder">
This will get replaced by handlebars.js</div>
<script type="text/javascript" src="Js/handlebars.min.js"></script>
<script type="text/javascript" src="Js/jquery-1.11.1.min.js"></script>
<script id="myTemplate" type="text/x-handlebars-template">
<h1>{{article }}</h1>
</script>
<script type="text/javascript">
var template = Handlebars.compile($("#myTemplate").html());
var conext = {
article: "Test",
};
$("#placeholder").html(template(conext));
</script>
</body>
</html>