SlideShare a Scribd company logo
Handlebars
Nelvin Driz
ndriz@exist.com
Handlebars.js
minimal templating on steroids
Handlebars
Who are the others?
Why use handlebars.js?
/人◕ ‿‿ ◕ 人\
Web Applications
Dynamic Interfaces
Cleaner and Simpler
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);
General Details


 Started by Yehuda Katz
 Built upon {{ Mustache }} (Logic-less templating)
 Compiles templates into a function
 No Dependencies
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>
Quick Example
#Template
{{#person}}
  {{../birthday/month}}
{{/person}}

#Data
var data = {
   person : { name : "name" }
, birthday: { month: "month" }
};

#Output
month
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);
{{Expression}}
{{Expression}}
Template
{{value}} {{fcn}} {{nothing}}
{{escaped}}
{{{notEscaped}}}

Data
var data = {
   value: “value”
, fcn : function() { return “function”; }
, escaped    : “<div>escaped<div>”
, notEscaped: “<div>not escaped</div>”
};

Output
value function  
&lt;div&gt;escaped&lt;/div&gt;
<div>not escaped</div>
{{Expression}}
 Simplest Dynamic Content
 Handlebar curly brace ( { / } )
 Contains (Value/Function/Nothing)
 Escapes Results by Default
   Use {{{Expression}}} to Unescape
   3 Pairs of Handlebars
Handlebars.Path/Nesting
Handlebars.Path/Nesting
#Template
{{#person}}
  {{../birthday/month}}
{{/person}}
{{person.firstName}} {{person/middleInit}}

#Data
var data = {
   person : { firstName : “name”
             , middleInit: “m”     }
, birthday: { month: "month" }
};

#Output
month
name m
Handlebars.Path/Nesting

{{this}} in a template means current context
dot ( . ) operator to inner context
deprecated forward-slash ( / )
dot dot ( .. ) operator to parent context
Chain-able
{{#Block}}{{/Block}}
{{#Block}}{{/Block}}


 start: Prepended by hash ( # )
 end: {{/Expression}} prepended by forward slash ( / )
 Change the context on the result of the {{#Expression}}
{{#if block}}{{/if}}

#Template
{{#if truthy}} truthy {{else}} falsy {{/if}}
{{#if falsy }} falsy {{else}} truthy{{/if}}

#Data
var data = {
   truthy: true
, falsy : false
};

#Output
truthy truthy
{{#unless block}}{{/unless}}
#Template
{{#unless truthy}} truthy {{else}} falsy {{/unless}}
{{#unless falsy }} falsy {{else}} truthy{{/unless}}
{{^falsy}} false {{/falsy}}
{{^zero }} truth {{/falsy}}

#Data
var data = {
   truthy: true
, falsy : false
, zero : 0
};

#Output
falsy falsy false
{{#each block}}{{/each}}
#Template
{{#each ul1}} {{this}}    {{/each}}
{{#each ul2}} {{li}}      {{/each}}
{{#each ul2}} {{this.li}} {{/each}}

#Data
var data = {
   ul1: [“li1”, “li2”]
, ul2: [{li: “li1”}, {li: “li2”}]
};

#Output
li1 li2
li1 li2
li1 li2
{{#with block}}{{/with}}
#Template
{{#with person}} {{firstName}} {{birthday}} {{/with}}

#Data
var data = {
   person: {
     firstName: “name”
   , birthday: “date”
   }
};

#Output
name date
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
Custom Expression Helpers
Custom Expression Helpers

#Helper
Handlebars.registerHelper(“greet”, function(fN, lN) {
  return “Hello, “ + fN + “ ” + lN “!”;
});

#Template
{{greet “firstName” “lastName”}}

#Output
Hello, firstName lastName!
Custom Expression Helpers


Use Handlebars.registerHelper(“helperName”, fcn);
function(parameters, ... , block) {};
Call like an {{Expression}}
Custom Block Helpers
Custom Block Helpers
#Helper
Handlebars.registerHelper(“modulo”, function(n, block) {
  if((n % 2) == 0) {
    return block();
  } else {
    return block.inverse();
  }
});

#Template
{{#modulo 10}} even {{else}} odd {{/modulo}}
{{#modulo 3 }} even {{else}} odd {{/modulo}}

#Output
even odd
Custom Block Helpers

Use Handlebars.registerHelper(“helperName”, fcn);
function(parameters, ... , trueBlock, falseBlock) {};
function(parameters, ... , block) {};
  trueBlock ~ block | falseBlock ~ block.inverse
Call like a {{#Block}}
Hash=Arguments (Helpers)
Hash=Arguments (Helpers)
#Helper
Handlebars.registerHelper(“gate”, function(block) {
  if(block.hash[“key”] == “open”)
    return block();
});

Handlebars.registerHelper(“gate2”, function(block) {
  return block.hash[“key”];
});

#Template
{{#gate key=”open”}}open{{/gate}}
{{gate key=”open”}}

#Output
open
open
Hash=Arguments (Helpers)


key=value pairs
Accessible through block.hash object
Partials


 Use Handlebars.registerPartial(“partialName”, tmpl);
 The partial may be a String or a Compiled Template
 Use {{> partialName}} inside template
Extra : Debugger

Handlebars.registerHelper(“debug”, function(optValue) {
  console.log(“Context”);
  console.log(“=========”);
  console.log(this);

  if(optionalValue) {
    console.log(“Value”);
    console.log(“=========”);
    console.log(optValue);
  }
});
Extra: Listener

#Helper
Handlebars.registerHelper(“listener”, function(block) {
  $(“#selector”).html(block(this));
  return “”;
});

#Template
{{#listener}}listened {{value}}{{/listener}}
Resources

http://www.handlebarsjs.com/
http://yehudakatz.com/2010/09/09/announcing-
handlebars-js/
http://thinkvitamin.com/code/getting-started-with-
handlebars-js/
Questions?

More Related Content

PPTX
Chronic kidney disease
Quratulann bader
 
PDF
Startup Snapshot in Node.js
Igalia
 
PDF
Tesi Marco Scopece "Analisi del fenomeno Sharing Economy"
Marco Scopece
 
PPTX
Hcv and renal disease
abdallah_haggag
 
PDF
Ig & complement-mediated glomerular dis with MPGN pattern (KDIGO 2021) - Dr.G...
NephroTube - Dr.Gawad
 
ZIP
Templating with your {{mustache}}js
Stefano Ceschi Berrini
 
PDF
Handlebars.js
Ivano Malavolta
 
KEY
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
Chronic kidney disease
Quratulann bader
 
Startup Snapshot in Node.js
Igalia
 
Tesi Marco Scopece "Analisi del fenomeno Sharing Economy"
Marco Scopece
 
Hcv and renal disease
abdallah_haggag
 
Ig & complement-mediated glomerular dis with MPGN pattern (KDIGO 2021) - Dr.G...
NephroTube - Dr.Gawad
 
Templating with your {{mustache}}js
Stefano Ceschi Berrini
 
Handlebars.js
Ivano Malavolta
 
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 

Similar to Handlebars (20)

PDF
JavaScript ES6
Leo Hernandez
 
KEY
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
PPT
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
PDF
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
PDF
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
PPT
Svcc Building Rich Applications with Groovy's SwingBuilder
Andres Almiray
 
KEY
CouchDB on Android
Sven Haiges
 
PPT
68837.ppt
BruceLee275640
 
PPT
Typescript - why it's awesome
Piotr Miazga
 
PPSX
What's New In C# 7
Paulo Morgado
 
PDF
Stuff you didn't know about action script
Christophe Herreman
 
PDF
Mongoskin - Guilin
Jackson Tian
 
KEY
Paris js extensions
erwanl
 
PPTX
Dartprogramming
Ali Parmaksiz
 
PDF
Functional programming using underscorejs
偉格 高
 
PDF
Play 2.0
elizhender
 
PPTX
Jquery optimization-tips
anubavam-techkt
 
PPTX
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
PDF
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
JavaScript ES6
Leo Hernandez
 
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Andres Almiray
 
CouchDB on Android
Sven Haiges
 
68837.ppt
BruceLee275640
 
Typescript - why it's awesome
Piotr Miazga
 
What's New In C# 7
Paulo Morgado
 
Stuff you didn't know about action script
Christophe Herreman
 
Mongoskin - Guilin
Jackson Tian
 
Paris js extensions
erwanl
 
Dartprogramming
Ali Parmaksiz
 
Functional programming using underscorejs
偉格 高
 
Play 2.0
elizhender
 
Jquery optimization-tips
anubavam-techkt
 
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
Ad

Recently uploaded (20)

PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Doc9.....................................
SofiaCollazos
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Doc9.....................................
SofiaCollazos
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Ad

Handlebars

Editor's Notes

  • #2: \n
  • #3: \n
  • #4: \n
  • #5: \n
  • #6: \n
  • #7: \n
  • #8: \n
  • #9: What if huge chunks of the document needs to change due to some event\n\n
  • #10: \n
  • #11: \n
  • #12: \n
  • #13: \n
  • #14: \n
  • #15: \n
  • #16: \n
  • #17: \n
  • #18: \n\n
  • #19: \n
  • #20: \n
  • #21: \n
  • #22: \n
  • #23: * If a block&amp;#x2019;s expression evaluates to anything other than an Array, Handlebars simply sets the context to the result of evaluating the expression.\n\n
  • #24: \n
  • #25: \n
  • #26: \n
  • #27: \n
  • #28: 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
  • #29: \n
  • #30: \n
  • #31: \n
  • #32: \n
  • #33: \n
  • #34: \n
  • #35: \n
  • #36: \n
  • #37: \n
  • #38: \n
  • #39: \n
  • #40: Basically Whenever the template here is used, the html of the element with id #selector is updated\n
  • #41: \n
  • #42: \n