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

转:http://rfyiamcool.blog.51cto.com/1030776/1278620

我们在开发的时候针对DOM操作,用简单的JS应用来说不成问题,但如果你对视图的每次更新都需要对我文档中非常大量的块进行操作呢?这时JS模版就派上用场了。

 

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

这是一个实例,我们可以把json的数据,按照自己的想法嵌入到模板里面。

Javascript模板引擎handlebars使用实例及技巧
<!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

看到这个例子,大家感觉很爽吧~  就是这样。。 我们可以通过后端取数据,然后扔到前端,而不用写各种 "" <> ‘‘的分离符号。

 

进行遍历里面的数据,print出来

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

  

有数据的话,进行数据渲染

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

  

没有数据的话,就写没有数据

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

 

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

 

Javascript模板引擎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的便签,通过开发者用具可以看到。

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

列表的话,有个和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  强大,但是他的优点很明显,就是小数据的展现还是相当的容易的。

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

上一篇:CSS:word-wrap/overflow/transition


下一篇:[Mugeda HTML5技术教程之16]案例分析:制作跨屏互动游戏