Fast Learning of Handlebars in 10 minutes and handlebars in 10 minutes

Source: Internet
Author: User

Fast Learning of Handlebars in 10 minutes and handlebars in 10 minutes
Front-end development whqet, csdn, Wang haiqing, whqet, front-end development expert

Original article: Learn Handlebars in 10 Minutes or Less

Translation: front-end development of whqet. The free translation is the main one. If not, please correct me.

Author profile: Danny Markov, tutorizine's bootstrap and html5 experts like to ride a bicycle or an angle code in the park in their spare time.

It is said that handlebars is a popular template engine that can separate html from javascript to write clearer code. Let's try it.

Certificate ----------------------------------------------------------------------------------------------------------------------------------------

After the gorgeous separation line, let's get down to the truth!

Certificate ----------------------------------------------------------------------------------------------------------------------------------------

Handlebars. js is a very popular and powerful template engine. It is easy to use and has a good learning community. It is based on the Mustache template engine and has made many improvements. With Handlebars, you can easily separate html from javascript code to write clearer code.

This article attempts to show you Handlebars in about ten minutes. It may take a long time to get started, but once you get started, everything will become simple.

0. Introduce the project

It is very easy to introduce Handlebars In the project. download the latest version (2.0.0 is the latest version when writing this article) at http://handlebarsjs.com/and then use the script tag to introduce it. Of course, you can also use cdn to enjoy the smooth speed of cdn. As shown in the code.

// From File<script src="handlebars-v2.0.0.js"></script>// From CDN<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
1. Templates

After you import the data to the database, we can happily write the template. The recommended method is to add the template using the script tag of the special type. The type attribute is very important, otherwise, the browser will regard them as parse Crip parsing.

A template has a very easy-to-understand syntax. You can use html, common text, and expressions. Expressions are usually contained in two or three pairs of curly braces and can contain variables or function functions. The template must be compiled before it can be used. As shown in the code below, I have put the case in codepen .. Note that we use jquery only to facilitate dom operations, handlebars can work well without jquery.

<! -- Template. --> <! -- The location where data is needed, which is included in. --> <script id = "address-template" type = "text/x-handlebars-template"> <p> You can find me in {city }}. my address is {number }}{ street }}. </p> </script> <! -- The new content is displayed here --> <div class = "content-placeholder"> </div>
$ (Function () {// capture template data var theTemplateScript =$ ("# address-template" ).html (); // compile the template var theTemplate = Handlebars. compile (theTemplateScript); // defines the data var context = {"city": "London", "street": "Baker Street", "number": "221B "}; // transfer data to the template var theCompiledHtml = theTemplate (context); // update it to the template ('.content-placeholder'apps.html (theCompiledHtml );});
2. Expressions

In the above case, any html code in the expression will be automatically ignored. This is a very practical performance, but sometimes we need to parse html, the following code uses three curly braces {{}} to demonstrate the effect in codepen.

In addition, the handlebars expression allows nested values so that we can easily access any value of a javascript Object.

<script id="expressions-template" type="text/x-handlebars-template">  {{description.escaped}}  {{example}}  <br><br>  {{description.unescaped}}  {{{example}}}</script><div class="content-placeholder"></div>
$ (Function () {// capture template data var theTemplateScript =$ ("# expressions-template" ).html (); // compile the template var theTemplate = Handlebars. compile (theTemplateScript); // defines the data var context = {"description": {"escaped": "Using {{}} brackets will result in escaped HTML :", "unescaped": "Using {{}} will leave the context as it is:" }," example ":" <button> Hello </button> "}; // transfer the data var theCompiledHtml = theTemplate (context); // display it on the page ('.content-placeholder'{.html (theCompiledHtml );});
3. Context

Handlebars utilizes the powerful features of Mustache, and context is one of them. We can put the data to be passed in this javascript Object, and use # each, # with and other methods to conveniently use the data of this object. After reading the following case, you will understand that the demonstration effect is in codepen.

<! -- # Each can traverse data. --> <script id = "example-template" type = "text/x-handlebars-template"> <! -- Traverse people -- >{# each people }}<! -- Directly use the data of each people --> <p >{{ firstName }}{{ lastName }}</p >{{/each }}</script>
$(function () {  var theTemplateScript = $("#example-template").html();  var theTemplate = Handlebars.compile(theTemplateScript);  var context = {    people: [       { firstName: 'Homer', lastName: 'Simpson' },      { firstName: 'Peter', lastName: 'Griffin' },      { firstName: 'Eric', lastName: 'Cartman' },      { firstName: 'Kenny', lastName: 'McCormick' },      { firstName: 'Bart', lastName: 'Simpson' }    ]  };  var theCompiledHtml = theTemplate(context);  $(document.body).append(theCompiledHtml);});
4. Helpers

Handlebars does not allow the use of javascript in the template, but provides some column functions (helpers) that can be called in the template to facilitate code reuse and create complex templates. The format of calling helpers using an expression is similar to that of {helpername}. You can also pass the parameter {helpname 12345 }}.

Develop a new helper and use registerHelper function. The following Code demonstrates how to create a new function, how to use a built-in function, and how to demonstrate the file in codepen.

<script id="built-in-helpers-template" type="text/x-handlebars-template">  {{#each animals}}    <p>      The {{capitalize this.name}} says      {{#if this.noise}}        "{{this.noise}}".      {{else}}        nothing since its a {{this.name}}.      {{/if}}    </p>  {{/each}}</script><div class="content-placeholder"></div>
$ (Function () {// defines a helper Handlebars. registerHelper ('capitalize', function (str) {// str is the argument passed to the helper when called str = str | ''; return str. slice (0, 1 ). toUpperCase () + str. slice (1) ;}); var theTemplateScript =$ ("# built-in-helpers-template" ..html (); var theTemplate = Handlebars. compile (theTemplateScript); var context = {animals: [{name: "cow", noise: "moooo"}, {name: "Cat", noise: "meow" },{ name: "fish", noise: "" },{ name: "farmer", noise: "Get off my property! "}]}; Var theCompiledHtml = theTemplate (context); Parameters ('.content-placeholder'apps.html (theCompiledHtml );});
5. Block helpers

Block helpers is like a common function, but has a start and end tag (similar to the built-in # if, # each, etc.). You can modify the html content. Creation is more complex, and the features are more powerful at that time. They are often used to reuse features and create a large segment of reusable html.

Similarly, use Handlebars. registerHelper () to create the block helper. The difference is that we need to use the second parameter, the callback function. Take a look at the following code and experience the powerful functions.

<script id="block-expressions-template" type="text/x-handlebars-template">  <p> The <b> {{#uppercase}} konami {{/uppercase}} </b> Code is a cheat code that appears in many video games.</p>  <p>During the title screen before the game demo begins, the player could press the following sequence of buttons on the game controller to enable the cheat:</p>  <p>{{#uppercase}}{{code}}{{/uppercase}}</p>  <p>The code is also present as an Easter egg on a number of websites.</p></script><div class="content-placeholder"></div>
$(function () {    var theTemplateScript = $("#block-expressions-template").html();  // This is our block helper  // The name of our helper is provided as the first parameter - in this case 'uppercase'  Handlebars.registerHelper('uppercase', function(options) {    // "this" is the context that existed when calling the helper.    // The options object has a special function - fn. This is a    // compiled version of the template that is contained between the opening and closing    // blocks of this helper. To get a string, call fn with the context:    return options.fn(this).toUpperCase();  });  var theTemplate = Handlebars.compile(theTemplateScript);  var context = {    "code": "up up down down left right left right b a select start"  };  var theCompiledHtml = theTemplate(context);  $('.content-placeholder').html(theCompiledHtml);});
6. Read resources and extensions

Now you have learned about the common functions of handlebars, and it is not a problem to learn more. You can go deep into the following resources.

Handlebars. js-official website for more cases and official documents

Try Handlebars. js-Try different application scenarios (based on the old version)

Handlebars Helpers-handlebars helpers set

SWAG-more

Handlebars API Reference-api documentation

----------------------------------------------------------

Front-end development whqet, pay attention to web Front-end development, share related resources, welcome to likes, welcome to shoot bricks.

Bytes ---------------------------------------------------------------------------------------------------------

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.