SlideShare une entreprise Scribd logo
1  sur  41
Nelvin Driz
ndriz@exist.com
Handlebars.js
minimal templating on steroids
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?

Contenu connexe

Tendances

Tendances (20)

Rails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power StackRails, Postgres, Angular, and Bootstrap: The Power Stack
Rails, Postgres, Angular, and Bootstrap: The Power Stack
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
jQuery
jQueryjQuery
jQuery
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
Nagios Conference 2014 - Troy Lea - JavaScript and jQuery - Nagios XI Tips, T...
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 
jQuery
jQueryjQuery
jQuery
 
Jquery
JqueryJquery
Jquery
 
jQuery
jQueryjQuery
jQuery
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
jQuery
jQueryjQuery
jQuery
 
Devoxx 2014-webComponents
Devoxx 2014-webComponentsDevoxx 2014-webComponents
Devoxx 2014-webComponents
 
Let's write secure drupal code!
Let's write secure drupal code!Let's write secure drupal code!
Let's write secure drupal code!
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
 
J query1
J query1J query1
J query1
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
 
Let's write secure Drupal code!
Let's write secure Drupal code!Let's write secure Drupal code!
Let's write secure Drupal code!
 

Similaire à Handlebars

CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
Christophe Herreman
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 

Similaire à Handlebars (20)

JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
68837.ppt
68837.ppt68837.ppt
68837.ppt
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesome
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 
Dartprogramming
DartprogrammingDartprogramming
Dartprogramming
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

Handlebars

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. What if huge chunks of the document needs to change due to some event\n\n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n\n
  18. \n
  19. \n
  20. \n
  21. \n
  22. * 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
  23. \n
  24. \n
  25. \n
  26. \n
  27. 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
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. Basically Whenever the template here is used, the html of the element with id #selector is updated\n
  40. \n
  41. \n