Javascript模板引擎handlebars使用實例及技巧

轉:http://rfyiamcool.blog.51cto.com/1030776/1278620javascript

咱們在開發的時候針對DOM操做,用簡單的JS應用來講不成問題,但若是你對視圖的每次更新都須要對我文檔中很是大量的塊進行操做呢?這時JS模版就派上用場了。html

 

源地址:http://rfyiamcool.blog.51cto.com/1030776/1278620前端

這是一個實例,咱們能夠把json的數據,按照本身的想法嵌入到模板裏面。java

<!DOCTYPE html>
<html>
  <head>
    <title>Handlebars Expressions Example</title>
  </head>
  <body>
    <h1>Handlebars Expressions Example!</h1>
<!--this is a list which will rendered by handlebars template.    -->
    <div id="list">
    </div>
                                                                                                                                                                                                                                                                                                                                                                                                           
    <script type="text/javascript" src=\'#\'" /jquery.js"></script>
    <script type="text/javascript" src=\'#\'" /handlebars-1.0.0.beta.6.js"></script>
                                                                                                                                                                                                                                                                                                                                                                                                           
    <script id="people-template" type="text/x-handlebars-template">
      {{#people}}
        <div class="person">
          <h2>{{first_name}} {{last_name}}</h2>
          <div class="phone">{{phone}}</div>
          <div class="email"><a href="mailto:{{email}}">{{email}}</a></div>
          <div class="since">User since {{member_since}}</div>
        </div>
      {{/people}}
    </script>
                                                                                                                                                                                                                                                                                                                                                                                                           
    <script type="text/javascript">
      $(document).ready(function() {
                                                                                                                                                                                                                                                                                                                                                                                                               
        // compile our template
        var template = Handlebars.compile($("#people-template").html());
                                                                                                                                                                                                                                                                                                                                                                                                               
        var data = {
          people: [
            { first_name: "rui", last_name: "fengyun", phone: "1234567890", email: "alan@test.com", member_since: "Mar 25, 2011" },
            { first_name: "Allison", last_name: "House", phone: "0987654321", email: "allison@test.com", member_since: "Jan 13, 2011" },
            { first_name: "Nick", last_name: "Pettit", phone: "9836592272", email: "nick@test.com", member_since: "Apr 9, 2009" },
            { first_name: "Jim", last_name: "Hoskins", phone: "7284927150", email: "jim@test.com", member_since: "May 21, 2010" },
            { first_name: "Ryan", last_name: "Carson", phone: "8263729224", email: "ryan@test.com", member_since: "Nov 1, 2008" }
          ]
        };
                                                                                                                                                                                                                                                                                                                                                                                                               
        $('#list').html(template(data));
      });
    </script>
  </body>
</html>
View Code

看到這個例子,你們感受很爽吧~  就是這樣。。 咱們能夠經過後端取數據,而後扔到前端,而不用寫各類 "" <> ''的分離符號。jquery

 

進行遍歷裏面的數據,print出來angularjs

<script id="each-template" type="text/x-handlebars-template">
  {{#each people}}
    ... output person's info here...
  {{/each}}
</script>

  

有數據的話,進行數據渲染ajax

<script id="each-template" type="text/x-handlebars-template">
  {{#if people}}
    ... output person's info here...
  {{/if}}
</script>

  

沒有數據的話,就寫沒有數據json

<script id="each-template" type="text/x-handlebars-template">
  {{#unless people.length}}
    There aren't any people.
  {{/unless}}
</script>

  

if else 關聯的判斷後端

 

<script id="each-template" type="text/x-handlebars-template">
  {{#if people.length}}
    ... output person's info here...
  {{else}}
    There aren't any people.
  {{/if}}
</script>

  

Handlebars.registerHelper('list', function (items, options)app

 

items是後面的key值,options是handlebars取值用的

 

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <title>Handlebars Block Expressions Example</title>
 5   </head>
 6   <body>
 7     <h1>Handlebars Expressions Example!</h1>
 8 <!--this is a list which will rendered by handlebars template.    -->
 9     <div id="list">
10     </div>
11                                                                                                                                                                                           
12     <script type="text/javascript" src=\'#\'" /jquery.js"></script>
13     <script type="text/javascript" src=\'#\'" /handlebars-1.0.0.beta.6.js"></script>
14                                                                                                                                                                                           
15     <script id="people-template" type="text/x-handlebars-template">
16         {{#list people}}
17             {{first_name}} {{last_name}}  {{phone}} {{email}} {{member_since}}
18         {{/list}}
19     </script>
20                                                                                                                                                                                           
21     <script type="text/javascript">
22       $(document).ready(function() {
23                                                                                                                                                                                               
24         // compile our template
25         var template = Handlebars.compile($("#people-template").html());
26         Handlebars.registerHelper('list', function (items, options) {
27             var out = "<div>";
28             for (var i = 0, l = items.length; i < l; i++) {
29                 out = out + "<div>" + "<h5>"+options.fn(items[i])+"</h5>" + "</div> jiewei";
30             }
31             return out + "</div>";
32         });
33         var data = {
34           people: [
35             { first_name: "Alan", last_name: "Johnson", phone: "1234567890", email: "alan@test.com", member_since: "Mar 25, 2011" },
36             { first_name: "Allison", last_name: "House", phone: "0987654321", email: "allison@test.com", member_since: "Jan 13, 2011" },
37             { first_name: "Nick", last_name: "Pettit", phone: "9836592272", email: "nick@test.com", member_since: "Apr 9, 2009" },
38             { first_name: "Jim", last_name: "Hoskins", phone: "7284927150", email: "jim@test.com", member_since: "May 21, 2010" },
39             { first_name: "Ryan", last_name: "Carson", phone: "8263729224", email: "ryan@test.com", member_since: "Nov 1, 2008" }
40           ]
41         };
42                                                                                                                                                                                               
43         $('#list').html(template(data));
44       });
45     </script>
46   </body>
47 </html>
View Code

我在value加了div和h5的便籤,經過開發者用具能夠看到。

列表的話,有個和jinja2很像的格式。

<div id="list">
    </div>
                                                                                                                   
    <script type="text/javascript" src=\'#\'" /jquery.js"></script>
    <script type="text/javascript" src=\'#\'" /handlebars-1.0.0.beta.6.js"></script>
                                                                                                                   
    <script id="people-template" type="text/x-handlebars-template">
      {{#each people}}
        <div class="person">
            {{this}}
        </div>
      {{/each}}
    </script>
                                                                                                                   
    <script type="text/javascript">
        $(document).ready(function () {
            // compile our template
            var template = Handlebars.compile($("#people-template").html());
            var data = {
                people: [
              "Alan Johnson" ,
              "Allison House" ,
              "Nick Pettit",
              "Jim Hoskins",
              "Ryan Carson"
            ]
            };
            $('#list').html(template(data));
        });
    </script>

  

要是想動態的抓數據,那就用ajax來搞。

$("button").click(function(){
  $.getJSON("demo_ajax_json.js",function(result){
   //result 就是值
    });
  });
});

  

咱們能夠把把result的值扔到模板裏面~

 

$(document).ready(function() {
            $('#btn1').click(function() {
                $.ajax({
                    type: "POST",   //使用Post方式請求
                    contentType: "application/json",
                    url: "Default2.aspx/HelloWorld",
                    data: "{}",  //這裏是要傳遞的參數,格式爲 data: "{paraName:paraValue}",下面將會看到   
                    dataType: 'json',   //會返回Json類型
                    success: function(result) {     //回調函數,result,返回值
                        //result 是咱們須要的值。。。。
                    }
                });
            });
        });
        //有參數調用

  

爲何使用 Handlebars.js? 

同意 

  • 它是一個弱邏輯模板引擎

  • 你能夠在服務端預編譯模板

  • 支持 Helper 方法

  • 能夠運行在客戶端和服務端

  • 在模板中支持 `this` 的概念

  • 它是 Mustache.js 的超集

  • 你能想到其餘的嗎?

反對 

  • 你能想到任何理由嗎?

總結~    這是一個很棒的js模板引擎~  固然功能上沒有backbone.js  angularjs.js  強大,可是他的優勢很明顯,就是小數據的展示仍是至關的容易的。

相關文章
相關標籤/搜索