Getting Started with Handlebars.js __js

Source: Internet
Author: User

With handlebars, you can easily create semantic templates, mustache templates and handlebars are compatible, so you can import mustache into handlebars to use handlebars powerful features. 1. Start

The handlebars template looks just like HTML, but embeds the handlebars expression

div class= "entry" >
  

The handlebars expression begins with {{}, with some content in the middle, ending with}}.

You can use <script> tags to introduce handlebars templates:

<script id= "Entry-template" type= "text/x-handlebars-template" >
  template content
</script>

Using Handlebars.compile to compile templates in javascript:

var Source = $ ("#entry-template"). html ();
var template = handlebars.compile (source);

You can also precompile your template, and then simply introduce a smaller Run-time library (handlebars.runtime.js) to avoid compiling in the browser and improving performance, which is more important in mobile devices.

In the incoming data context, handlebars executes and generates HTML:

var context = {title: ' My New Post ', body: ' This is my post! '}
var html    = template (context);

The results obtained are:

<div class= "Entry" >
  
2, HTML coding

In handlebars, {{expression}} will return a coded HTML, and if you do not want to be encoded, you can use the {{{}

<div class= "Entry" >
  

Use such a data context:

{
  title: ' All About <p> Tags ', body
  : ' <p>this is a post about &lt;p&gt; Tags</p> "
}

The result:

<div class= "Entry" >
  

Handlebars does not encode handlebars.safestring. If you customize a helper, return a section of HTML code, you need to return to new handlebars.safestring (result). At this point, you need to encode the content manually:

Handlebars.registerhelper (' link ', function (text, URL) {
    text = Handlebars.Utils.escapeExpression (text);
    URL  = Handlebars.Utils.escapeExpression (URL);

    var result = ' <a href= ' + URL + ' > ' + text + ' </a> ';

    Return to new handlebars.safestring (result);
});

This will encode the parameters passed in, and the return value is "safe", so even if you do not use {{{} handlebars will not encode it again. 3, block expression

Block expressions allow you to define a helper and invoke a template in a different data context. Here we define a helper that builds the list:

{{#list people}} {{FirstName}}} {{LastName}}} {{/list}}}

If our data is like this:

{
  people: [
    {firstName: "Yehuda", LastName: "Katz"},
    {firstName: "Carl", LastName: "Lerche"},
    { FirstName: "Alan", LastName: "Johnson"}
  ]
}

We create a helper named list to generate the list, and the helper accepts people as the first argument, and a option object (hash) as the second argument. Option contains a property FN, which he can call a context just like a Normal template.

Handlebars.registerhelper (' list ', function (items, options) {
      var out = ' <ul> ';

      For (Var i=0, l=items.length. i<l; i++) {out
        = out + "<li>" + Options.fn (Items[i]) + "</li>";
      } Return out

      + "</ul>";
});

After execution, get:

<ul>
  <li>yehuda katz</li>
  <li>carl lerche</li>
  <li>alan Johnson</li>
</ul>

Block expressions have many attributes, for example, you can create an else block (the built-in if helper has an else block). In addition, if the OPTIONS.FN (context) encodes the content, handlebars will not encode the helper content, or it will be coded twice. 4, Handlebars path

Handlebars support for simple paths

<p>{{name}}</p>

Nested paths are also supported to find properties at the next level

<div class= "Entry" >
  
This template uses the following data:
var context = {
  title: ' My post! ',
  Author: {
    id:47,
    name: "Yehuda Katz"
  }, Body
  : " My I-post. wheeeee! "
};

Nested paths are also supported. /,

var data = {
  permalink: ' http://keenwon.com ',
  comments: [
    {id:1,title: ' link 1 ', Body: ' Link 1 '},
    {id:2, Title: ' Link 2 ', Body: ' Link 2 '}
  ]
};

Handlebars can resolve problems with helpers and data naming conflicts through this reference.

<p>{{./name}} or {This/name}} or {{this.name}}</p>
5. Template Note {{!}}} or {!––} }

You can comment in handlebars Riga:

<div class= "Entry" >
  {! Only output this author names if a author}
  {{#if exists}}
    author FirstName}} {{lastname}}

Comments do not appear in the output, and if you want to display them, you can use an HTML annotation (which will be executed and then displayed as an annotation, so if there is an error in the HTML annotation, it will still be an error).

<div class= "Entry" >
  {{! This comment will not appear in the output}}
  <!--will show-->
</div>
All annotations must contain the end tag '} ', and multiline annotations can use ' {{!––}} ' ———- 6, Helpers

Handlebars helpers can read any data context in the template, you can use Handlebars.registerhelper to register a helpers.

<div class= "POST" >
  

Then use the following data context and helpers:

var context = {
  Author: {firstName: ' Alan ', lastName: ' Johnson '}, Body
  : ' I love handlebars ',
  comments: [{
  
   author: {firstName: "Yehuda", LastName: "Katz"}, Body
    : "Me too!"
  }]
};

Handlebars.registerhelper (' FullName ', function (person) {return
  Person.firstname + "" + Person.lastname;
});
  

The result:

<div class= "POST" >
  

Use this to access the current context

<ul>
  {{#each items}}
  <li>{{agree_button}}</li>
  {/each}}
</ul>

Use the following helpers and data contexts

var context = {
  items: [
    {name: ' Handlebars ', Emotion: ' Love '},
    {name: ' Mustache ', emotion: ' Enjoy '},
    { Name: "Ember", Emotion: "Want to Learn"}
};

Handlebars.registerhelper (' Agree_button ', function () {return
  new handlebars.safestring (
    "<button>i Agree. I "+ this.emotion +" "+ THIS.name +" </button> "
  );

The result:

<ul>
  <li><button>i agree. I Love handlebars</button></li>
  <li><button>i agree. I enjoy mustache</button></li>
  <li><button>i agree. I want to learn ember</button></li>
</ul>
If your helpers returns an HTML fragment, don't want to be coded. Must be new a ' handlebars.safestring ' back out. Built in Helpers The WITH block Helper

Typically, handlebars will pass the data context to the compilation method:

var source   = "<p>{{lastname}}, {{firstname}}</p>";
var template = handlebars.compile (source);
Template ({firstName: "Alan", LastName: "Johnson"});
Results:
<p>johnson, alan</p>

Use with to change the current context

<div class= "Entry" >
  
The data context is as follows:
{
  title: "My A-post!",
  Author: {
    firstName: "Charles",
    lastName: "Jolley"
  }
}

Results:

<div class= "Entry" >
  
The each block helper

You can use the built-in each helper to generate a list that you can use to access the current item.

<ul class= "People_list" >
  {{#each people}}
  <li>{{this}}</li>
  {/each}}
</ul >

The data context is as follows:

{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley"
  ]
}

Results:

<ul class= "People_list" >
  <li>yehuda katz</li>
  <li>alan johnson</li> <li>charles jolley</li>
</ul>

You can use this to refer to the current context in any context

In addition, you can use the {{else}} block to display the contents of {else}} when the contents of the list are empty

{{#each paragraphs}}
  <p>{{this}}</p>
{Else}}
  <p class= "Empty" > No content </p>
{{/each}}

When you loop through each item in each, you can use the {{@index}} to get the current ordinal number.

{{#each array}}
  {{{@index </

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.