Handlebars.js使用介绍

原文:Learn Handlebars in 10 Minutes or Less

翻译:前端开发whqet, 意译为主,不当之处敬请指正。

作者简介:Danny Markov ,Tutorialzine的bootstrap和html5方面的专家,业余时间喜欢骑自行车或在公园的某个角度码码。

译者的话:据说handlebars是一个流行的模板引擎,可以把html从javascript中分离出来,写更清晰的代码。来不妨一试。

Handlebars.js是一个非常流行的功能强大的模板引擎,简单易用,具备较好的学习社区。它基于 Mustache 模板引擎,并且做了诸多改进。利用Handlebars您可以方便的把html从javascript代码中分离出来,从而书写更清晰的代码。

本文章试图通过十分钟左右的时间带您领略Handlebars的风采,刚开始学的时候可能费点周折,但是您一旦上手,一切将变得很简单。

0.引入项目

在项目中引入Handlebars非常简单,到 http://handlebarsjs.com/下载最新版本(本文写作时,最新版为2.0.0),然后使用script标签引入即可。当然您也可以使用cdn的方式,享受cdn方式的畅快。如代码所示。

[javascript] view plain copy
  1. // From File  
  2. <script src="handlebars-v2.0.0.js"></script>  
  3.   
  4. // From CDN  
  5. <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>  

1.Templates

当您引入库之后,我们可以愉快的书写模板了,推荐的方式是通过特殊type的script标签来添加模板,type属性是非常重要的,否则浏览器会将它们看做javascrip解析。

模板具有一个很容易理解的语法,可以使用html、普通文本和表达式,表达式通常被包含在两对或三对花括号里,可以包含变量或功能函数。模板需要编译之后才能使用,如下面代码所示,案例我放在了codepen,大家不妨一看。。注意一点,我们使用了jquery仅仅为了方便dom操作,handlebars可以脱离jquery良好工作。

[html] view plain copy
  1. <!--模板. -->  
  2. <!--需要数据的地方,用{{}}括起来.-->  
  3. <script id="address-template" type="text/x-handlebars-template">  
  4.   <p>You can find me in {{city}}. My address is {{number}} {{street}}.</p>  
  5. </script>  
  6.   
  7. <!--新的内容在这里展示-->  
  8. <div class="content-placeholder"></div>  
[javascript] view plain copy
  1. $(function () {  
  2.   // 抓取模板数据  
  3.   var theTemplateScript = $("#address-template").html();  
  4.   
  5.   // 编译模板  
  6.   var theTemplate = Handlebars.compile(theTemplateScript);  
  7.   
  8.   // 定义数据  
  9.   var context={  
  10.     "city""London",  
  11.     "street""Baker Street",  
  12.     "number""221B"  
  13.   };  
  14.   
  15.   // 把数据传送到模板  
  16.   var theCompiledHtml = theTemplate(context);  
  17.   
  18.   // 更新到模板  
  19.   $('.content-placeholder').html(theCompiledHtml);  
  20. });  

2. Expressions

上面所示的案例,表达式中的任何html代码将会被自动忽略,这是一个非常实用的性能,但是有的时候我们需要解析html,那么就要用三个花括号{{{ }}},如下面代码所示,演示效果在codepen

另外,handlebars表达式允许嵌套值,可以方便我们访问javascript对象的任何值。

[html] view plain copy
  1. <script id="expressions-template" type="text/x-handlebars-template">  
  2.   {{description.escaped}}  
  3.   {{example}}  
  4.   
  5.   <br><br>  
  6.   
  7.   {{description.unescaped}}  
  8.   {{{example}}}  
  9. </script>  
  10.   
  11. <div class="content-placeholder"></div>  
[javascript] view plain copy
  1. $(function () {  
  2.   // <span style="font-family:Arial, Helvetica, sans-serif;">抓取模板数据</span>  
  3.   var theTemplateScript = $("#expressions-template").html();  
  4.   
  5.   // 编译模板  
  6.   var theTemplate = Handlebars.compile(theTemplateScript);  
  7.   
  8.   // 定义数据  
  9.   var context={  
  10.     "description": {  
  11.       "escaped""Using {{}} brackets will result in escaped HTML:",  
  12.       "unescaped""Using {{{}}} will leave the context as it is:"  
  13.     },  
  14.     "example""<button> Hello </button>"  
  15.   };  
  16.   
  17.   // 传送数据  
  18.   var theCompiledHtml = theTemplate(context);  
  19.   
  20.   // 展示到页面  
  21.   $('.content-placeholder').html(theCompiledHtml);  
  22. });  

3. Context

Handlebars利用了Mustache的强大特性,context就是其中之一。我们可以把需要传递的数据放在这个javascript对象中,使用#each、#with等方法可以方便的使用该对象的数据。看了下面这个案例,那就明白了,演示效果在codepen

[html] view plain copy
  1. <!-- #each可以遍历数据. -->  
  2. <script id="example-template" type="text/x-handlebars-template">  
  3.   
  4.   <!-- 遍历people -->  
  5.   
  6.   {{#each people}}  
  7.   
  8.     <!-- 直接使用每个people的数据 -->  
  9.     <p>{{firstName}} {{lastName}}</p>  
  10.   
  11.   {{/each}}  
  12.   
  13. </script>  
[javascript] view plain copy
  1. $(function () {  
  2.   var theTemplateScript = $("#example-template").html();  
  3.   
  4.   var theTemplate = Handlebars.compile(theTemplateScript);  
  5.   
  6.   var context = {  
  7.     people: [   
  8.       { firstName: 'Homer', lastName: 'Simpson' },  
  9.       { firstName: 'Peter', lastName: 'Griffin' },  
  10.       { firstName: 'Eric', lastName: 'Cartman' },  
  11.       { firstName: 'Kenny', lastName: 'McCormick' },  
  12.       { firstName: 'Bart', lastName: 'Simpson' }  
  13.     ]  
  14.   };  
  15.   
  16.   var theCompiledHtml = theTemplate(context);  
  17.   
  18.   $(document.body).append(theCompiledHtml);  
  19. });  

4. Helpers

Handlebars不允许在模板中使用javascript,而是提供了一些列的功能函数(helpers),可以在模板中调用,方便代码重用和创造复杂模板。使用表达式调用helpers的格式类似如此,{{helpername}},同时也可以传递参数,{{helpname 12345}}。

开发新的helper,使用registerHelper function,下面代码演示了如何创建新的功能函数,如何使用内置的功能函数,演示文件在codepen

[html] view plain copy
  1. <script id="built-in-helpers-template" type="text/x-handlebars-template">  
  2.   {{#each animals}}  
  3.     <p>  
  4.       The {{capitalize this.name}} says  
  5.       {{#if this.noise}}  
  6.         "{{this.noise}}".  
  7.       {{else}}  
  8.         nothing since its a {{this.name}}.  
  9.       {{/if}}  
  10.     </p>  
  11.   {{/each}}  
  12. </script>  
  13.   
  14. <div class="content-placeholder"></div>  
[javascript] view plain copy
  1. $(function () {  
  2.   
  3.   // 定义a helper  
  4.   Handlebars.registerHelper('capitalize'function(str){  
  5.     // str is the argument passed to the helper when called  
  6.     str = str || '';  
  7.     return str.slice(0,1).toUpperCase() + str.slice(1);  
  8.   });  
  9.   
  10.   var theTemplateScript = $("#built-in-helpers-template").html();  
  11.   
  12.   var theTemplate = Handlebars.compile(theTemplateScript);  
  13.   
  14.   var context = {  
  15.     animals:[  
  16.       {  
  17.         name: "cow",  
  18.         noise: "moooo"  
  19.       },  
  20.       {  
  21.         name: "cat",  
  22.         noise: "meow"  
  23.       },  
  24.       {  
  25.         name: "fish",  
  26.         noise: ""  
  27.       },  
  28.       {  
  29.         name: "farmer",  
  30.         noise: "Get off my property!"  
  31.       }  
  32.     ]  
  33.   };  
  34.   
  35.   var theCompiledHtml = theTemplate(context);  
  36.   
  37.   $('.content-placeholder').html(theCompiledHtml);  
  38.   
  39. });  

5. Block helpers

Block helpers像普通的功能函数一样,但是有开始和结束标签(类似于内置的#if、#each等),可以修改包含的html的内容。创建更为复杂一些,当时功能更加强大。经常使用它们重复使用功能、创建一大段可重用的html等。

同样使用Handlebars.registerHelper()创建block helper,不同的是我们需要使用第二参数,回调函数。看看下面的代码,体会强大功能

[html] view plain copy
  1. <script id="block-expressions-template" type="text/x-handlebars-template">  
  2.   
  3.   <p> The <b> {{#uppercase}} konami {{/uppercase}} </b> Code is a cheat code that appears in many video games.</p>  
  4.   
  5.   <p>During the title screen before the game demo begins, the player could press the following sequence of buttons on the game controller to enable the cheat:</p>  
  6.   
  7.   <p>{{#uppercase}}{{code}}{{/uppercase}}</p>  
  8.   
  9.   <p>The code is also present as an Easter egg on a number of websites.</p>  
  10.   
  11. </script>  
  12.   
  13. <div class="content-placeholder"></div>  
[javascript] view plain copy
  1. $(function () {  
  2.     
  3.   var theTemplateScript = $("#block-expressions-template").html();  
  4.   
  5.   // This is our block helper  
  6.   // The name of our helper is provided as the first parameter - in this case 'uppercase'  
  7.   Handlebars.registerHelper('uppercase'function(options) {  
  8.   
  9.     // "this" is the context that existed when calling the helper.  
  10.   
  11.     // The options object has a special function - fn. This is a  
  12.     // compiled version of the template that is contained between the opening and closing  
  13.     // blocks of this helper. To get a string, call fn with the context:  
  14.   
  15.     return options.fn(this).toUpperCase();  
  16.   
  17.   });  
  18.   
  19.   var theTemplate = Handlebars.compile(theTemplateScript);  
  20.   
  21.   var context = {  
  22.     "code""up up down down left right left right b a select start"  
  23.   };  
  24.   
  25.   var theCompiledHtml = theTemplate(context);  
  26.   
  27.   $('.content-placeholder').html(theCompiledHtml);  
  28.   
  29. });  

6.资源和延伸阅读

现在你基本上了解了handlebars的常用功能,同样再多学点也问题不大,您可以通过以下资源深入学习。

Handlebars.js-官方网站,可以获取更多案例、官方文档

Try Handlebars.js-尝试不同的应用情境(基于老版本)

Handlebars Helpers-handlebars helpers集

SWAG-更多

Handlebars API Reference -api文档

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值