A Preliminary Study on the JavaScript template engine-HandleBars

Source: Internet
Author: User

A Preliminary Study on the JavaScript template engine-HandleBars

?? Handlebars is a Javascript template engine that allows you to easily and efficiently write semantic templates. It is an extension of the Mustache template engine. Both Handlebars and Mustache are logic-less templates) the Web Front-end view and data can be separated to reduce coupling between the two.
?? Handlebars is characterized by expressions, no APIs for operating data, no HTML tags, and similar to DeDeCMS and WordPress templates. Therefore, Handlebars can be easily used with other front-end JS libraries (such as jQuery) mixed, easy to write, and easy to expand. Handlebars supports the following browsers and runtime environments: Internet Explorer 6 +, Google Chrome, Firefox, Safari 5 +, Opera 11 +, and Node. js. Handlebars is the default template engine of Ember. js and is also the default template engine based on Node. js frameworks Clouda + and Meteor.

Download

?? You can download its js file from the official HandleBars website and add it to your project. If your Web project already has a folder named js that specifically stores JavaScript files, this location is an excellent choice. The following example shows the project structure in WebStorm.

Usage

?? First, introduce the external JavaScript files of HandleBars and jQuery in the project. Note that jQuery is not a must, but you must admit that it is a very good JavaScript library, and it fulfills "write less, more "(Write Less, Do More) Commitment, using the powerful selector provided by jQuery and its encapsulation of DOM and Ajax operations can save a lot of trouble. Therefore, in the following project, I add both HandleBars and jQuery to the HTML page.

<script type="text/javascript" src="js/handlebars.js"></script> <script type="text/javascript" src="js/jquery.js"></script>

?? HandleBars templates are almost identical to common HTML pages. we add a piece of content to the above Code.

{{title}} {{greeting}} <script type="text/javascript" src="js/handlebars.js"></script> <script type="text/javascript" src="js/jquery.js"></script>

?? In the above Code, the HandleBars expression is used. The HandleBars expression is written in {{... . Next, we will make the code we just added into a template. It is easy to use a <script> tag to enclose the code.

<script id="foo" type="text/x-handlebars-template"> {{title}} {{greeting}} </script> <script type="text/javascript" src="js/handlebars.js"></script> <script type="text/javascript" src="js/jquery.js"></script>

?? The next step is to use HandleBars to process the preceding template and generate the page content. The expression is equivalent to the placeholder in the template and will be replaced by the corresponding value, the replacement expression value can be written in JSON format. The Code is as follows.

<script id="foo" type="text/x-handlebars-template"> {{title}} {{greeting}} </Script> <script type = "text/javascript" src = "js/handlebars. js "> </script> <script type =" text/javascript "src =" js/jquery. js "> </script> <script type =" text/javascript "> var templateSection = $ (" # foo "); // obtain the element with ID foo (template code segment) var sourceCode = templateSection.html (); // obtain the HTML code var template = Handlebars of the template section. compile (sourceCode); // use the compile of Handlebars to compile the template var context = {title: "Hello, world! ", Greeting:" This is a simple example of HandleBars "}; // Save the data in JSON var targetCode = template (context ); // Replace the placeholder in the template with the corresponding data to get the final HTML code templateSection. replaceWith (targetCode); // replace the original template segment with the final HTML code. </script>

?? Note that if the string that replaces the placeholder contains the object replacement character (for example, all rights reserved? , Currency symbol $, right angle bracket>), so when writing the HandleBars expression should use {{{... }}}, You can try the following code.

<script id="foo" type="text/x-handlebars-template"> {{{title}}} {{greeting}} </Script> <script type = "text/javascript" src = "js/handlebars. js "> </script> <script type =" text/javascript "src =" js/jquery. js "> </script> <script type =" text/javascript "> var templateSection = $ (" # foo "); var sourceCode = templateSection.html (); var template = Handlebars. compile (sourceCode); var context = {title: "Hello, world! & Gt; ", greeting:" This is a simple example using HandleBars "}; // note that the string contains the entity replacement character var targetCode = template (context); templateSection. replaceWith (targetCode); </script>

?? HandleBars's most exciting feature should be block expressions and a custom helper (Block expression processor). The following example demonstrates the use of block expressions.

<script id="foo" type="text/x-handlebars-template"> {{{title}}} {{greeting}} {{# Foreach persons }{{ name }}: {age }{{/foreach }}</script> <script type = "text/javascript" src = "js/handlebars. js "> </script> <script type =" text/javascript "src =" js/jquery. js "> </script> <script type =" text/javascript "> // register a helper (Block expression processor) Handlebars. registerHelper ("foreach", function (items, options) {var out ="
  • "; for(var i = 0, len = items.length; i < len; ++i) { out += "
    • " + options.fn(items[i]) + "
    • "; } return out + "
    ";}); Var templateSection = $ (" # foo "); var sourceCode = templateSection.html (); var template = Handlebars. compile (sourceCode); var context = {title: "Hello, world! & Gt; ", greeting:" This is a simple example using HandleBars ", persons: [{name:" Hao LUO ", age: 34}, {name: "Wang Damai", age: 25}, {name: "Zhang Sanfeng", age: 120}]}; var targetCode = template (context); templateSection. replaceWith (targetCode); </script>

?? Let's look at another example.

<script id="foo" type="text/x-handlebars-template"> {{{title}}} {{greeting}} {{! -- The following is a block expression -- }}{{# foreach persons }}{{ f name }}{{ t gender }}: {age }{{/foreach }}</script> <script type = "text/javascript" src = "js/handlebars. js "> </script> <script type =" text/javascript "src =" js/jquery. js "> </script> <script type =" text/javascript "> // register a helper (Block expression processor) Handlebars. registerHelper ("foreach", function (items, options) {var out ="
  • "; for(var i = 0, len = items.length; i < len; ++i) { out += "
    • " + options.fn(items[i]) + "
    • "; } return out + "
    ";}); // F helper extracts the last name Handlebars from the name. registerHelper ("f", function (name) {return name. charAt (0); // It is assumed that all Chinese names are single surnames (only a small example, not true or false )}); // t helper outputs Mr or MS Handlebars based on gender. registerHelper ("t", function (gender) {return gender? "Sir": "" ;}); var templateSection =$ ("# foo"); var sourceCode = templateSection.html (); var template = Handlebars. compile (sourceCode); var context = {title: "Hello, world! & Gt; ", greeting:" This is a simple example of HandleBars. ", persons: [{name:" ", gender: true, age: 34 }, {name: "", gender: false, age: 25}, {name: "Zhang Sanfeng", gender: true, age: 120}]}; var targetCode = template (context); templateSection. replaceWith (targetCode); </script>

?? Shows the running effect.

?? Of course, HandleBars has built-in the most commonly used block processor.

If: if the parameter value is false, undefined, null, "", 0, or [], HandlerBars will not render the block expression. The Code is as follows:
 
{{#if author}}  
{{firstName}} {{lastName}} 
{{/if}}  

?? That is to say, if the above Code does not have the author definition in the context, the following output will be generated:

  
Unless: opposite to if. Each: You can iterate the array. During iteration, you can also use {@ index} to represent the nth loop, and use {@ key} to represent the attribute name of the object.
 
  • {{#each persons}}
    • {{this}}
    • {{/each}}

    ?? The Context data is as follows:

    {Persons: ["Yan Hao", "Wang dameng", "Zhang Sanfeng"]}

    ?? For more information, visit the official HandleBars website about the built-in help tool.

    ?? You can use Ajax functions encapsulated by jQuery to obtain Context Data in JSON format from the server. The Code is as follows:

    $.getJSON("HelloServlet", {}, function(context) {    var targetCode = template(context);    templateSection.replaceWith(targetCode);});

    ?? The official HandleBars website also provides a reference manual for HandleBars.

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.