handlebar.js模板引擎(輕頁面小工程可用)

介紹

Handlebars 讓你可以有能力高效地容易地創立語義化的模版。Handlebars兼容Mustache語法,在大多數狀況下它能夠讀取Mustache的語法並在你當前模板中使用。具體點擊這裏javascript

安裝

  1. 下載
  2. npm install --save handlebars
  3. bower install --save handlebars

具體參考css

開始使用

Handlebars 模板看起來就像嵌套handlebars表達式的規範的HTML。html

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

handlebars表達式: {{ cnt }}
你也能夠經過<script>標籤包裹handlebars表達式傳遞模板給瀏覽器:java

<script id="entry-template" type="text/x-handlebars-template">
  <div class="entry">
    <h1>{{title}}</h1>
    <div class="body">
      {{body}}
    </div>
  </div>
</script>
你必須把模板放在 <script>標籤裏,這很重要。不要直接把它放在HTML中不然HTML的解析會改變模板內容。

JavaScript中,使用Handlebars.compile來編譯模板:jquery

var source   = $("#entry-template").html();
var template = Handlebars.compile(source);
// ‘entry-template’就是包裹模板的script的id
注意這種方法在產品應用中不推薦使用。更好的方法是預編譯你的模版。這將使要求的運行庫更小,模板沒必要在瀏覽器中編譯,顯著地節省了時間。這在移動設備上尤其重要。

在JavaScript中,使用Handlebars.compile()方法來預編譯模板 例如:(這是一套規則)git

//用jquery獲取模板
var tpl   =  $("#tpl").html();
//原生方法
var source = document.getElementById('#tpl').innerHTML;
//預編譯模板
var template = Handlebars.compile(source);
//模擬json數據
var context = { name: "zhaoshuai", content: "learn Handlebars"};
//匹配json內容
var html = template(context);
//輸入模板
$(body).html(html);

經過解析context處理handlebars模板獲取HTML內容github

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

輸出html:express

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

HTML轉碼

Handlebars 的轉碼HTML值經過{{expression}}返回. 若是你不想handlebars轉碼一個值的話,使用{{{expression}}}npm

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

上下文內容:json

{
  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. 若是你寫了輸出自己所含HTML的輔助 helper, 你其實想返回一個新的Handlebars.SafeString.在這種狀況下,你想手動拼接參數.

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

這樣能夠避免字符串被轉碼,正確響應參數,即便你不適用{{{也不會被轉碼。

塊級表達式

塊級表達式 容許你定義一個能夠觸發一個與當前不一樣的上下文來替換模板的相應內容的helper。這些塊級輔助helper經過在helper的名字前加#並在結束時名字前加/:

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

渲染context:

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

咱們會建立一個叫list的helper輸出HTML列表。該列表以people爲第一個參數,哈希選項爲第二個參數。這些選項裏包含一條名爲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>

塊級輔助helper有不少特色,例如能夠建立一個else部分.由於當你調用options.fn(context)時塊級helper的內容已經被轉碼過,因此handlebars不會再去轉碼helper的內容。

handler 的路徑

Handlebars 支持簡單的路徑,就像 Mustache.

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

Handlebars 也支持嵌套的屬性,好比對象的屬性.

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

  <div class="body">
    {{body}}
  </div>
</div>

模板工做的對象context:

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>

{{permalink}}
{{#each comments}}
  {{../permalink}}

  {{#if title}}
    {{../permalink}}
  {{/if}}
{{/each}}

這裏例子中引用了相同的permalink即便他們在不一樣的塊中。這種行爲是新的,handlebars4支持。

Handlebars的內置塊表達式(Block helper)

  1. each block helper
    你可使用內置的{{#each}} helper遍歷列表塊內容,用this來引用遍歷的元素 例如:

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

    對應適用的json數據

    {
           name: ["html","css","javascript"]
       };

    這裏的this指的是數組裏的每一項元素,和上面的Block很像,但原理是不同的這裏的name是數組,而內置的each就是爲了遍歷數組用的,更復雜的數據也一樣適用。

  2. if else block helper
    {{#if}}就你使用JavaScript同樣,你能夠指定條件渲染DOM,若是它的參數返回false,undefined, null, "" 或者 [] (a "falsy" value), Handlebar將不會渲染DOM,若是存在{{#else}}則執行{{#else}}後面的渲染。

    {{#if list}}
       <ul id="list">  
           {{#each list}}
               <li>{{this}}</li>
           {{/each}}
       </ul>  
       {{else}}
           <p>{{error}}</p>
       {{/if}}

    對應適用json數據

    var data = {info:['HTML5','CSS3',"WebGL"],"error":"數據取出錯誤"}

    這裏{{#if}}判斷是否存在list數組,若是存在則遍歷list,若是不存在輸出錯誤信息

  3. unless block helper
    {{#unless}}這個語法是反向的if語法也就是當判斷的值爲false時他會渲染DOM 例如:

    {{#unless data}}
       <ul id="list">  
           {{#each list}}
               <li>{{this}}</li>
           {{/each}}
       </ul>  
       {{else}}
           <p>{{error}}</p>
       {{/unless}}
  4. with block helper
    {{#with}}通常狀況下,Handlebars模板會在編譯的階段的時候進行context傳遞和賦值。使用with的方法,咱們能夠將context轉移到數據的一個section裏面(若是你的數據包含section)。 這個方法在操做複雜的template時候很是有用。

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

    對應適用json數據

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

Handlebar的註釋(comments)

Handlebars也可使用註釋寫法以下

{{! handlebars comments }}

Handlebars的訪問(Path)

Handlebar支持路徑和mustache,Handlebar還支持嵌套的路徑,使得可以查找嵌套低於當前上下文的屬性
能夠經過.來訪問屬性也可使用../,來訪問父級屬性。 例如:(使用.訪問的例子)

<h1>{{author.id}}</h1>

對應json數據

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

例如:(使用../訪問)

{{#with person}}
    <h1>{{../company.name}}</h1>
{{/with}}

對應適用json數據

{
    "person":
    { "name": "Alan" },
        company:
    {"name": "Rad, Inc." }
};

自定義helper

Handlebars,能夠從任何上下文能夠訪問在一個模板,你可使用Handlebars.registerHelper()方法來註冊一個helper。

調試技巧

把下面一段"debug helper"加載到你的JavaScript代碼裏,而後在模板文件裏經過{{debug}}或是{{debug someValue}}方便調試數據

Handlebars.registerHelper("debug", function(optionalValue) {  
  console.log("Current Context");
  console.log("====================");
  console.log(this);
  if (optionalValue) {
    console.log("Value");
    console.log("====================");
    console.log(optionalValue);
  }
});

handlebars的jquery插件

(function($) {
    var compiled = {};
    $.fn.handlebars = function(template, data) {
        if (template instanceof jQuery) {
            template = $(template).html();
        }
    compiled[template] = Handlebars.compile(template);
    this.html(compiled[template](data));
    };
})(jQuery);
$('#content').handlebars($('#template'), { name: "Alan" });
相關文章
相關標籤/搜索