In this video we’ll learn Handlebars by walking through numerous examples. Handlebars is a superset of the Mustache template engine. A template engine helps you separate your HTML from dynamic content created by languages such as JavaScript.
We’ll look at how to dynamically place data, templates, working with arrays, helper functions, passing attributes, escaping strings for safety, block helpers, fn, inverse, partials, precompiling templates and much more.
If you like videos like this, it helps me when you tell Google with a click here [googleplusone]
Code from the Video
handlebarstut.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!-- Handlebars is a superset of the Mustache template engine. A template engine helps you separate your HTML from dynamic content created by languages such as JavaScript. --> <!DOCTYPE html> <html> <head> <title>Hello Handlebars</title> <!-- You can download Handlebars at http:// handlebarsjs.com/ and save it as handlebars-v4.0.2.js on your site. Then make it available by adding the following line. --> <script src="handlebars-v4.0.2.js"></script> <!-- NodeJS is needed to precompile your templates so that your pages load faster. Install it by going to NodeJS.org and then type the following in your terminal to install Handlebars CLI : npm install -g handlebars--> <!-- <script id="result-template" type="text/x-handlebars-template"> </script> --> </head> <body> <!-- The information will be placed in this div --> <div id="derekData"></div> <script type="text/javascript"> // Structure how I want the data to dynamically be // placed by defining the keys in between {{}} var myInfo = "<p>My name is {{name}} and I live at {{street}} in {{city}}, {{state}}</p>"; // Generate a JS function that will create the output var template = Handlebars.compile(myInfo); // template receives the key / value pairs and puts // them in place var data = template({name: "Derek", street: "123 Main St", city: "Pittsburgh", state: "PA"}); // Update the div with the completed output document.getElementById('derekData').innerHTML += data; </script> </body> </html> |
handlebarstut2.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
<!DOCTYPE html> <html> <head> <title>Hello Handlebars</title> <style type="text/css"> .redText {color: red;} .blueText {color: blue;} .greenText {color: green;} </style> <!-- You can download Handlebars at http:// handlebarsjs.com/ and save it as handlebars-v4.0.2.js on your site. Then make it available by adding the following line. --> <script src="handlebars-v4.0.2.js"></script> </head> <body> <div id="quoteData"></div> <!-- It is better to separate your template from the JS and you do that by placing the template in its own tag --> <script id="quote-template" type="text/x-handlebars-template"> <h3>Favorite {{name}} Quotes</h3> <ol> {{!-- 2. The each helper can insert an array of data --}} {{#each quotes}} <li>{{quote}}</li> {{/each}} </ol> {{!-- 3. You can use Html tags with triple-stash --}} {{{yogiBio}}}<br /><br /> {{!-- 4. Call to custom Helper function, which will generate html tags without the triple-stash --}} {{makeLink "Yogi Berra Museum" "http://yogiberramuseum.org/"}}<br /> {{!-- 5. Pass attributes to a Helper --}} {{changeColor "Make my text red" color="blue"}}<br /> {{!-- 6. Say hello in defined language --}} {{sayHello}} </script> <script type="text/javascript"> var quoteInfo = document.getElementById("quote-template").innerHTML; var template = Handlebars.compile(quoteInfo); // 4b. You can create your own helper functions // This returns a link when text and url are passed in // escapeExpression() escapes the passed string so it is // safe to use in content. Helpers should use this method // when returning content to avoid code injection Handlebars.registerHelper("makeLink", function(text, url){ text = Handlebars.Utils.escapeExpression(text); url = Handlebars.Utils.escapeExpression(url); var theLink = '<a href="' + url + '">' + text + '</a>'; // SafeString prevents the string from being escaped return new Handlebars.SafeString(theLink); }); // 5b. Pass an attribute to a helper function Handlebars.registerHelper("changeColor", function(text, options){ text = Handlebars.Utils.escapeExpression(text); // You can access the attributes by name if(options.hash.color === "red"){ return new Handlebars.SafeString("<span class='redText'>" + text + "</span>"); } else if(options.hash.color === "blue"){ return new Handlebars.SafeString("<span class='blueText'>" + text + "</span>"); } else { return new Handlebars.SafeString("<span class='greenText'>" + text + "</span>"); } }); // 6b. You can also pass options that can be used by all // helpers in the template Handlebars.registerHelper("sayHello", function(options){ switch(options.data.lang){ case "spanish": return "Hola"; break; case "french": return "Bonjour"; break; default: return "Hello"; } }); // 2b. Passing the array data var quoteData = template({ name: "Yogi Berra", quotes: [ {quote: "If you don't know where you are going, you might wind up someplace else."}, {quote: "You better cut the pizza in four pieces because I'm not hungry enough to eat six."}, {quote: "I never said most of the things I said."}, {quote: "Nobody goes there anymore because it's too crowded."} ], // 3b. Passing tags to the triple stash yogiBio: '<i>Lawrence Peter "Yogi" Berra (May 12, 1925 - September 22, 2015) was an American professional baseball catcher, manager, and coach who played 19 seasons in Major League Baseball (MLB) (1946 - 63, 1965), all but the last for the New York Yankees. An 18-time All-Star and 10-time World Series champion as a player, Berra had a career batting average of .285, while compiling 358 home runs and 1,430 runs batted in.</i>' } // 6c. Say hello in passed language , {data: { lang: "spanish" } }); document.getElementById('quoteData').innerHTML += quoteData; </script> </body> </html> |
handlebarstut3.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<!DOCTYPE html> <html> <head> <title>Hello Handlebars</title> <script src="handlebars-v4.0.2.js"></script> </head> <body> <div id="contentDiv"></div> <script id="the-template" type="text/x-handlebars-template"> {{!-- 7. Block helper that receives the name value for the radio buttons --}} {{#makeRadio "size"}} Small Medium Large {{/makeRadio}} {{!-- 8. You can place an {{else}} tag in your block helpers to create alternative template functions. Here well check for equality of 2 passed values --}} {{#areEqual 1 1}} Numbers are equal {{else}} Numbers are not equal {{/areEqual}}<br /> {{!-- 9. Handlebars has a built in if conditional that we can use to display different results --}} {{#if "isActive"}} <img src="ntt-logo.png" alt="Active"> {{else}} <img src="ntt-logo-horz.png" alt="Inactive"> {{/if}} </script> <script type="text/javascript"> // Assign the template name var templateInfo = document.getElementById("the-template").innerHTML; // Compile the template var template = Handlebars.compile(templateInfo); // 7b. Create the helper that generates radio buttons Handlebars.registerHelper("makeRadio", function(name, options){ // Save the string that the function returns var radioList = options.fn(); // Split the results at the \n radioList = radioList.trim().split("\n"); var output = ""; // Cycle through the results and place them in radio elements for(var val in radioList){ var item = radioList[val].trim(); output += '<input type="radio" name="' + name + '" value="' + item + '">' + item + '<br />'; } return output; }); // 8b. 2 values are passed and depending on equality we will // execute fn() or inverse() Handlebars.registerHelper("areEqual", function(num1, num2, options){ if(num1 === num2){ return options.fn(this); } else { return options.inverse(this); } }); // 9b. In a similar way we can display different results // based on a value passed into our function Handlebars.registerHelper("if", function(data, options){ if(data === "isActive"){ return options.fn(this); } else { return options.inverse(this); } }); // If there is nothing to pass keep this blank var templateData = template({}); document.getElementById('contentDiv').innerHTML += templateData; </script> </body> </html> |
handlebarstut4.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<!DOCTYPE html> <html> <head> <title>Hello Handlebars</title> <script src="handlebars-v4.0.2.js"></script> </head> <body> <div id="contentDiv"></div> <script id="the-template" type="text/x-handlebars-template"> {{!-- 10. You can use with to refer to a nested parameter --}} <div class="potter-1"> <h3>{{title}}</h3> {{#with techData}} <div class="isbn">{{{isbn}}}</div> <div class="author">{{{author}}}</div> {{/with}} </div><br /> {{!-- Otherwise you would use the following --}} <div class="potter-2"> {{title}} by {{techData.author}} </div> </script> <script type="text/javascript"> // Assign the template name var templateInfo = document.getElementById("the-template").innerHTML; // Compile the template var template = Handlebars.compile(templateInfo); Handlebars.registerHelper('with', function(context, options) { // Here we are passed the context which points to the // techData part of our data return options.fn(context); }); var templateData = template({ title: "Harry Potter and the Philosopher's Stone", techData: { isbn: "0-7475-3269-9", author: "J. K. Rowling" } }); document.getElementById('contentDiv').innerHTML += templateData; </script> </body> </html> |
handlebarstut5.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<!DOCTYPE html> <html> <head> <title>Hello Handlebars</title> <script src="handlebars-v4.0.2.js"></script> </head> <body> <div id="contentDiv"></div> <script id="the-template" type="text/x-handlebars-template"> {{!-- 11. Partials provide code reuse, but unlike helpers they dont compute anything, but instead work like placeholders for data. --}} {{> myName }} {{!-- 12. We can call for data in the partial and define the tag to surround it --}} <div class="post"> {{> askQuestion tagName="h2" }} <h2>Suggestions</h2> {{!-- We can cycle through all comments passed and also define the surrounding tag --}} {{#each comments}} {{> askQuestion tagName="h3" }} {{/each}} </div> </script> <script type="text/javascript"> // Assign the template name var templateInfo = document.getElementById("the-template").innerHTML; // Compile the template var template = Handlebars.compile(templateInfo); // 11b. A partial is registered with registerPartial Handlebars.registerPartial('myName', '{{name}}'); // 12. Define the partial name and then substitute the // passed tags and the data Handlebars.registerPartial('askQuestion', '<{{tagName}}>{{author}}</{{tagName}}>' + '<div class="comment">{{comment}}</div>'); var templateData = template({ name: "Derek", author: "John Smith", comment: "Where should we vacation?", comments: [{ author: "Sue Smith", comment: "The beach" }, { author: "Paul Smith", comment: "Disneyworld" }] }); document.getElementById('contentDiv').innerHTML += templateData; </script> </body> </html> |
handlebarstut6.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html> <head> <title>Hello Handlebars</title> <script src="handlebars-v4.0.2.js"></script> </head> <body> <div id="contentDiv"></div> <!-- Compile with handlebars groceries.handlebars -f groceries.js --> <script id="grocery-template" type="text/x-handlebars-template"> {{#each groceries}} <div class='grocery-item'> <p>Item: {{this.item}} </p> </div> {{/each}} </script> <script type="text/javascript"> var templateInfo = document.getElementById("grocery-template").innerHTML; var template = Handlebars.compile(templateInfo); var context = { groceries:[ {item: "Potato"}, {item: "Flour"}, {item: "Yogurt"}, {item: "Beans"} ] } var templateData = template(context); document.getElementById('contentDiv').innerHTML += templateData; </script> </body> </html> |
handlebarstut7.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!DOCTYPE html> <html> <head> <title>Hello Handlebars</title> <script src="handlebars-v4.0.2.js"></script> <script src="groceries.js"></script> </head> <body> <div id="contentDiv"></div> <!-- Compile with handlebars groceries.handlebars -f groceries.js --> <script type="text/javascript"> // var templateInfo = document.getElementById("grocery-template").innerHTML; // var template = Handlebars.compile(templateInfo); var template = Handlebars.templates['groceries']; var context = { groceries:[ {item: "Potato"}, {item: "Flour"}, {item: "Yogurt"}, {item: "Beans"} ] } var templateData = template(context); document.getElementById('contentDiv').innerHTML += templateData; </script> </body> </html> |
groceries.handlebars
1 2 3 4 5 |
{{#each groceries}} <div class='grocery-item'> <p>Item: {{this.item}} </p> </div> {{/each}} |
Leave a Reply