Handlebars.js Template engine

Source: Internet
Author: User
Tags script tag

Introduced

Handlebars is a JavaScript semantic template library that quickly builds web templates by separating view and data. It uses the idea of "logic-less template" (no logical template) to be precompiled at load time, rather than to compile when the client executes to the code, which guarantees the speed of the template to load and run. Handlebars compatible with mustache, you can import mustache templates in handlebars.

Use and Installation

Handlebars installation is very simple, you only need to download the latest version from GitHub, you can also visit the following URL to get the latest information: http://handlebarsjs.com.
At present Handlebars.js has been widely used in many projects, handlebars is a pure JS library, so you can use the same as other JS script to include the script tag handlebars.js

Basic syntax

Handlebars expressions is the most basic unit in the handlebars template, using the method is to add two curly braces {{value}} , handlebars template will automatically match the corresponding values, objects and even functions.
For example:

<div class= "Demo" >      

It's important that you create a template, ID (or Class) and type, because you want to use them to get template content such as:

<script id= "TPL" type= "Text/x-handlebars-template" >  <div class= "Demo" >          

Handlebars automatically matches the expression based on context, and if the match is a variable, the value of the variable is output, and if the match is a function, the function is called.
If no match is found, there is no output. Expressions also support point operators, so you can use {{content.title}} this form to invoke nested values or methods, and handlebars outputs the value of the title property of the content variable based on the current context.

In JavaScript, use Handlebars.compile() methods to precompile templates such as: (This is a set of rules)

//get templates with jquery    varTPL = $ ("#tpl"). html (); //Native Methods    varSource = document.getElementById (' #tpl '). InnerHTML; //Pre-compiled templates    varTemplate =handlebars.compile (source); //simulating JSON data    varContext = {name: "Zhaoshuai", Content: "Learn Handlebars"}; //Match JSON content    varHTML =template (context); //Enter a template$ (body). HTML (HTML);
Handlebar expression Block Expression

Sometimes when you need to go deeper into an expression, blocks comes in handy, and in handlebars you can follow the expression with a # sign to represent blocks, and then {{/表达式}} end the blocks. If the current expression is an array, handlebars "Automatically expands the array" and sets the context of the blocks to an element in the group. For example:

<ul>  {#programme}}    <li>{{language}}</li>{{/programme}}</ul>  

Has the following JSON data

{  programme: [    "JavaScript"},    "HTML"},    "CSS"}  ]}

Compile template Code ditto ... The code above automatically matches the programme data and expands the data, which is what happens after the DOM is rendered.

<ul>    <li>JavaScript</li>  <li>HTML</li>  <li>CSS</li> </ul>  
Handlebars built-in block helper 1.each block helper

You can use the built-in {{#each}} helper to iterate through the contents of a list block and use it this to refer to traversed elements such as:

<ul>      {{#each name}}        <li>{{this}}</li>    {{/each}}</ul>  

Corresponds to the applicable JSON data

{    name: ["html", "CSS", "JavaScript"]};

This this refers to each element in the array, much like the block above, but the principle is not the same. Here the name is an array, and the built-in each is for iterating over the array, and the more complex data is equally applicable.

2.if Else Block Helper{{#if}}Just like you use JavaScript, you can specify conditions to render the DOM, if its parameters returnfalse,undefined, null, "" 或者 [] (a "falsy" value), handlebar will not render the DOM if it exists{{#else}}The execution{{#else}}The subsequent rendering
For example:
{{#if  list}}<ul id= "list" >      {{#each list}}        <li>{{This}} </li>    {{/each}}</ul>  {else}}    <p>{{error}}</p>{{/if}}

Corresponds to the applicable JSON data

var data = {      info:[' HTML5 ', ' CSS3 ', "WebGL"],    "error": "Data fetch error"} 

This {{#if}} determines whether a list array exists, and if so, iterates through the list if there is no output error message

3.unless Block Helper

{{#unless}}This syntax is the inverse if syntax, which is that when the value is judged false he will render the DOM for example:

{{#unless data}}<ul id= "list" >      {{#each list}}        <li>{{this}}</li >    {{/each}}</ul>  {else}}    <p>{{error}}</p>{{/unless}}
4.with Block Helper

{{#with}}In general, the handlebars template will be passed and assigned in the context of the compile phase. Using the With method, we can transfer the context to a section of the data (if your data contains a section). This method is useful when working with complex template.

<div class= "Entry" >     with author}}   

Corresponds to the applicable JSON data

{  "My first post!" ,  Author: {    "Charles",    "Jolley"  }}
Handlebar's Notes (comments)

Handlebars can also be used as a notation

{{! Handlebars comments}}
Handlebars Access (Path)

Handlebar supports paths and mustache , handlebar also supports nested paths, making it possible to find properties that are nested below the current context
You can access . ../ the Parent property by accessing the property or by using it. Example: (using . the access example)

Corresponding JSON data

{  "My first Blog post!" ,  Author: {        "Yehuda Katz"  },  "My first post." wheeeee! "   };

Example: (Use ../ access)

{{# with Person }}     {{/with}}

Corresponds to the applicable JSON data

{    "person":    "name": "Alan" }, Company        :    {"name": "Rad, Inc."  }};
Custom Helper

Handlebars can be accessed from any context in a template, and you can use the Handlebars.registerHelper() method to register a helper.

Debugging Tips

Load the following section of "Debug helper" into your JavaScript code, then pass through the template file {{debug}} or {{debug someValue}} easily debug the data

function (optionalvalue) {    console.log ("Current Context");  Console.log ("====================");  Console.log (this);   if (optionalvalue) {    console.log ("Value");    Console.log ("====================");    Console.log (Optionalvalue);  }});
Handlebars's jquery Plugin
(function($) {    var compiled = {};     function (template, data) {        ifinstanceof  jQuery) {            = $ (template). html ( );        }     = Handlebars.compile (template);      This . HTML (compiled[template] (data);    };}) (jQuery); $ (' #content '). Handlebars ($ (' #template '), {name: "Alan"});

The main application to mobile development above, I give you two pictures, you will understand

The same is two HTML the first document is 10kb the second one is 20KB and obviously saves traffic. Now the cost of traffic is very expensive Oh!

Handlebars.js Template engine

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.