10. Example
#Given a JSON Data
var data = { items: [{text: “Hello World”}, ... ]};
#Normal JS
var div = document.createElement(“div”),
items = data.item;
for(var i = 0; i < data.item.length) {
div.append(items[i].text);
}
#With Handlebars.js
var html = “<div>{{#each items}}{{text}}{{/each}}</div>”;
var template = Handlebars.compile(html);
template.html(data);
11. General Details
Started by Yehuda Katz
Built upon {{ Mustache }} (Logic-less templating)
Compiles templates into a function
No Dependencies
12. Guidelines
Using jQuery v1.6.2
Using Handlebars.js 1.0.0 beta3
Templates are surrounded by:
<script type=”text/x-handlebars-template” name=”x” id=”x”></script>
13. Quick Example
#Template
{{#person}}
{{../birthday/month}}
{{/person}}
#Data
var data = {
person : { name : "name" }
, birthday: { month: "month" }
};
#Output
month
14. Javascript Flow
/* Data */
var data = {
person : { name : "name" }
, birthday: { month: "month" }
};
/* Get Template */
var html = $(“#selector”).html();
/* Compile */
var template = Handlebars.compile(html);
/* Generate HTML using template */
template(data);
22. {{#Block}}{{/Block}}
start: Prepended by hash ( # )
end: {{/Expression}} prepended by forward slash ( / )
Change the context on the result of the {{#Expression}}
27. Global Block Helpers
Special Parameters ( . / .. / this )
Built in block helpers:
{{#each}} , {{#if}} , {{#unless}} , {{#with}}
Special Expressions:
{{else}} Used for {{#if}} and {{#unless}}
{{^expression}} just like {{#unless}} but not on zero
What if huge chunks of the document needs to change due to some event\n\n
\n
\n
\n
\n
\n
\n
\n
\n
\n\n
\n
\n
\n
\n
* If a block&#x2019;s expression evaluates to anything other than an Array, Handlebars simply sets the context to the result of evaluating the expression.\n\n
\n
\n
\n
\n
Special Parameters: (dot) (dot dot) this\n\neach - iterate through array\nif - truthy (any value except undefined, null, 0, false)\nunless - falsy (only values with undefined, null, 0, false)\n\ntip #arrays use array.length\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
Basically Whenever the template here is used, the html of the element with id #selector is updated\n