Handlebars中文文檔(譯自官方版)

Handlebars 爲你提供了一個能夠毫無挫折感的高效率書寫 語義化的模板 所必需的一切。 javascript

Mustache 模板和 Handlebars 是兼容的,因此你能夠把Mustache模板拿來導入到Handlebars中,並開始使用Handlebars所提供的更豐富的功能。 css

開始

Handlebars模板看起來就像是正常的Html,並使用了嵌入的 handlebars 表達式。 html

<div class="entry"> <h1>{{title}}</h1> <div class="body"> {{body}} </div> </div>

handlebars表達式,是以 {{ 開始,跟一些內容,而後以 }} 結束。
更多資料:表達式 java


你能夠經過<script>標籤把一段模板加載到瀏覽器中。 express

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

在 JavaScript 中使用 Handlebars.compile 來編譯模板。 segmentfault

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

還能夠預編譯模板。這樣的話,就只須要一個更小的運行時庫文件,而且對性能來講是一個極大的節約,由於這樣就沒必要在瀏覽器中編譯模板了。這點在移動版的開發中就更顯的很是重要了。
更多資料:預編譯 瀏覽器


只需傳遞一個上下文context執行模板,便可獲得返回的 HTML 的值
(譯者注:一般來講在 js 中上下文就決定了當前函數的this的指向) 安全

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

獲得下面的HTML bash

<div class="entry"> <h1>My New Post</h1> <div class="body"> This is my first post! </div> </div>

更多資料:執行 less


Handlebars的 {{expression}} 表達式會返回一個 HTML編碼 HTML-escape 過的值。若是不但願Handlebars來編碼這些值,使用三個大括號便可:{{{。

<div class="entry"> <h1>{{title}}</h1> <div class="body"> {{{body}}} </div> </div>

使用這段上下文(數據):

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

會獲得以下結果:

<div class="entry"> <h1>All About &lt;p&gt; Tags</h1> <div class="body"> <p>This is a post about &lt;p&gt; tags</p> </div> </div>

Handlebars 不會再對 Handlebars.SafeString 安全字符串進行編碼。若是你寫的 helper 用來生成 HTML,就常常須要返回一個 new Handlebars.SafeString(result)。在這種狀況下,你就須要手動的來編碼參數了。

Handlebars.registerHelper('link', function(text, url) {
  text = Handlebars.Utils.escapeExpression(text);
  url  = Handlebars.Utils.escapeExpression(url); var result = '<a href="' + url + '">' + text + '</a>'; return new Handlebars.SafeString(result);
});

這樣來編碼傳遞進來的參數,並把返回的值標記爲 安全,這樣的話,即使不是喲給你「三個大括號」,Handlebars 就不會再次編碼它了。

塊級表達式

塊級表達式容許你定義一個helpers,並使用一個不一樣於當前的上下文(context)來調用你模板的一部分。如今考慮下這種狀況,你須要一個helper來生成一段 HTML 列表:

{{#list people}}{{firstName}} {{lastName}}{{/list}}

並使用下面的上下文(數據):

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

此時須要建立一個 名爲 list 的 helper 來生成這段 HTML 列表。這個 helper 使用 people 做爲第一個參數,還有一個options 對象(hash哈希)做爲第二個參數。這個 options 對象有一個叫 fn 的屬性,你能夠傳遞一個上下文給它(fn),就跟執行一個普通的 Handlebars 模板同樣:

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>";
});

執行以後,這個模板就會渲染出:

<ul> <li>Yehuda Katz</li> <li>Carl Lerche</li> <li>Alan Johnson</li> </ul>

塊級的 helpers 還有不少其餘的特性,好比能夠建立一個 else 區塊(例如,內置的 if helper 就是用 else)。

注意,由於在你執行 options.fn(context) 的時候,這個 helper 已經把內容編碼一次了,因此 Handlebars 不會再對這個 helper 輸出的值進行編碼了。若是編碼了,這些內容就會被編碼兩 次!
更多資料:塊級Helpers
譯文在此

Handlebars 路徑

Handlebars 支持簡單的路徑,就像Mustache那樣。

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

Handlebars 一樣也支持嵌套的路徑,這樣的話就能夠在當前的上下文中查找內部嵌套的屬性了。

<div class="entry"> <h1>{{title}}</h1> <h2>By {{author.name}}</h2> <div class="body"> {{body}} </div> </div>

上面的模板使用下面這段上下文:

var context = { title: "My First Blog Post!", author: { id: 47, name: "Yehuda Katz" }, body: "My first post. Wheeeee!" };

這樣一來 Handlebars 就能夠直接把JSON數據拿來用了。

巢狀嵌套的 handlebars 路徑也可使用 ../, 這樣會把路徑指向父級(上層)上下文。

<h1>Comments</h1> <div id="comments"> {{#each comments}} <h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2> <div>{{body}}</div> {{/each}} </div>

儘管 a 連接在輸出時是以 comment 評論爲上下文的,但它仍然能夠退回上一層的上下文(post上下文)並取出permalink(固定連接)值。
(譯者注)上下文數據應該以下所示(源文檔並無給出)

var context = { post: { body:'這是文章內容', permalink: 'http://xx.com/xx', comments:[{ title:'這篇文章不錯,贊一個' },{ title:'好文要頂!' }]
  }
}

../ 標識符表示對模板的父級做用域的引用並不表示在上下文數據中的上一層。這是由於塊級 helpers 能夠以任何上下文來調用一個塊級表達式,因此這個【上一層】的概念用來指模板做用域的父級更有意義些。

Handlebars也容許經過一個 this 的引用來解決 helpers 和 數據字段間的名字衝突:

<p>{{./name}} or {{this/name}} or {{this.name}}</p>

上面的這一種方式都會將 name 字段引用到當前上下文上,而不是 helper 上的同名屬性。

模板註釋:{{! }} 或 {{!-- --}}

你能夠在 handlebars 代碼中加註釋,就跟在代碼中寫註釋同樣。對於有必定程度的邏輯的部分來講,這卻是一個很好的實踐。

<div class="entry">
  {{! only output this author names if an author exists }}
  {{#if author}} <h1>{{firstName}} {{lastName}}</h1>
  {{/if}}
</div>

註釋是不會最終輸出到返回結果中的。若是你但願把註釋展現出來,就使用 HTML 的註釋就好了。

<div class="entry"> {{! This comment will not be in the output }} <!-- This comment will be in the output --> </div>

全部註釋都必須有 }},一些多行註釋可使用 {{!-- --}} 語法。

Helpers

Handlebars 的 helpers 在模板中能夠訪問任何的上下文。能夠經過 Handlebars.registerHelper 方法註冊一個 helper。

<div class="post"> <h1>By {{fullName author}}</h1> <div class="body">{{body}}</div> <h1>Comments</h1> {{#each comments}} <h2>By {{fullName author}}</h2> <div class="body">{{body}}</div> {{/each}} </div>

當時用下面的上下文數據和 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;
});

會獲得以下結果:

<div class="post"> <h1>By Alan Johnson</h1> <div class="body">I Love Handlebars</div> <h1>Comments</h1> <h2>By Yehuda Katz</h2> <div class="body">Me Too!</div> </div>

Helpers 會把當前的上下文做爲函數中的 this 上下文。

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

當使用下面的 this上下文 和 helpers:

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>" );
});

會獲得以下結果:

<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>

若是你不但願你的 helper 返回的 HTML 值被編碼,就請務必返回一個 new Handlebars.SafeString

內置的 Helpers

with helper

通常狀況下,Handlebars 模板在計算值時,會把傳遞給模板的參數做爲上下文。

var source   = "<p>{{lastName}}, {{firstName}}</p>"; var template = Handlebars.compile(source);
template({firstName: "Alan", lastName: "Johnson"});

結果以下:

<p>Johnson, Alan</p>

不過也能夠在模板的某個區域切換上下文,使用內置的 with helper便可。

<div class="entry"> <h1>{{title}}</h1> {{#with author}} <h2>By {{firstName}} {{lastName}}</h2> {{/with}} </div>

在使用下面數據做爲上下文時:

{ title: "My first post!", author: { firstName: "Charles", lastName: "Jolley" }
}

會獲得以下結果:

<div class="entry"> <h1>My first post!</h1> <h2>By Charles Jolley</h2> </div>

each helper

你可使用內置的 each helper 來循環一個列表,循環中可使用 this 來表明當前被循環的列表項。

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

使用這個上下文:

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

會獲得:

<ul class="people_list"> <li>Yehuda Katz</li> <li>Alan Johnson</li> <li>Charles Jolley</li> </ul>

事實上,可使用 this 表達式在任何上下文中表示對當前的上下文的引用。

還能夠選擇性的使用 else ,當被循環的是一個空列表的時候會顯示其中的內容。

{{#each paragraphs}} <p>{{this}}</p>
{{else}}
  <p class="empty">No content</p>
{{/each}}

在使用 each 來循環列表的時候,可使用 {{@index}} 來表示當前循環的索引值。

{{#each array}} {{@index}}: {{this}}
{{/each}}

對於 object 類型的循環,可使用 {{@key}} 來表示:

{{#each object}} {{@key}}: {{this}}
{{/each}}

if helper

if 表達式能夠選擇性的渲染一些區塊。若是它的參數返回 false, undefined, null, "" 或 [](譯註:還有 0)(都是JS中的「假」值),Handlebars 就不會渲染這一塊內容:

<div class="entry">
  {{#if author}} <h1>{{firstName}} {{lastName}}</h1>
  {{/if}}
</div>

當時用一個空對象({})做爲上下文時,會獲得:

<div class="entry">
</div>

在使用 if 表達式的時候,能夠配合 {{else}} 來使用,這樣當參數返回 假 值時,能夠渲染 else 區塊:

<div class="entry">
  {{#if author}} <h1>{{firstName}} {{lastName}}</h1>
  {{else}}
    <h1>Unknown Author</h1>
  {{/if}}
</div>

unless helper

unless helper 和 if helper 是正好相反的,當表達式返回假值時就會渲染其內容:

<div class="entry">
  {{#unless license}} <h3 class="warning">WARNING: This entry does not have a license!</h3>
  {{/unless}}
</div>

若是在當前上下文中查找 license 返回假值,Handlebars 就會渲染這段警告信息。反之,就什麼也不輸出。

log helper

log helper 能夠在執行模板的時候輸出當前上下文的狀態。

{{log "Look at me!"}}

這樣會把委託信息發送給 Handlebars.logger.log,並且這個函數能夠重寫來實現自定義的log。

相關文章
相關標籤/搜索