10分钟快速学Handlebars

前端开发whqet,csdn,王海庆,whqet,前端开发专家

原文: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方式的畅快。如代码所示。

// From File
<script src="handlebars-v2.0.0.js"></script>

// From CDN
<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良好工作。

<!--模板. -->
<!--需要数据的地方,用{{}}括起来.-->
<script id="address-template" type="text/x-handlebars-template">
  <p>You can find me in {{city}}. My address is {{number}} {{street}}.</p>
</script>

<!--新的内容在这里展示-->
<div class="content-placeholder"></div>
$(function () {
  // 抓取模板数据
  var theTemplateScript = $("#address-template").html();

  // 编译模板
  var theTemplate = Handlebars.compile(theTemplateScript);

  // 定义数据
  var context={
    "city": "London",
    "street": "Baker Street",
    "number": "221B"
  };

  // 把数据传送到模板
  var theCompiledHtml = theTemplate(context);

  // 更新到模板
  $('.content-placeholder').html(theCompiledHtml);
});

2. Expressions

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

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

<script id="expressions-template" type="text/x-handlebars-template">
  {{description.escaped}}
  {{example}}

  <br><br>

  {{description.unescaped}}
  {{{example}}}
</script>

<div class="content-placeholder"></div>
$(function () {
  // 抓取模板数据
  var theTemplateScript = $("#expressions-template").html();

  // 编译模板
  var theTemplate = Handlebars.compile(theTemplateScript);

  // 定义数据
  var context={
    "description": {
      "escaped": "Using {{}} brackets will result in escaped HTML:",
      "unescaped": "Using {{{}}} will leave the context as it is:"
    },
    "example": "<button> Hello </button>"
  };

  // 传送数据
  var theCompiledHtml = theTemplate(context);

  // 展示到页面
  $('.content-placeholder').html(theCompiledHtml);
});

3. Context

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

<!-- #each可以遍历数据. -->
<script id="example-template" type="text/x-handlebars-template">

  <!-- 遍历people -->

  {{#each people}}

    <!-- 直接使用每个people的数据 -->
    <p>{{firstName}} {{lastName}}</p>

  {{/each}}

</script>
$(function () {
  var theTemplateScript = $("#example-template").html();

  var theTemplate = Handlebars.compile(theTemplateScript);

  var context = {
    people: [ 
      { firstName: 'Homer', lastName: 'Simpson' },
      { firstName: 'Peter', lastName: 'Griffin' },
      { firstName: 'Eric', lastName: 'Cartman' },
      { firstName: 'Kenny', lastName: 'McCormick' },
      { firstName: 'Bart', lastName: 'Simpson' }
    ]
  };

  var theCompiledHtml = theTemplate(context);

  $(document.body).append(theCompiledHtml);
});

4. Helpers

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

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

<script id="built-in-helpers-template" type="text/x-handlebars-template">
  {{#each animals}}
    <p>
      The {{capitalize this.name}} says
      {{#if this.noise}}
        "{{this.noise}}".
      {{else}}
        nothing since its a {{this.name}}.
      {{/if}}
    </p>
  {{/each}}
</script>

<div class="content-placeholder"></div>
$(function () {

  // 定义a helper
  Handlebars.registerHelper('capitalize', function(str){
    // str is the argument passed to the helper when called
    str = str || '';
    return str.slice(0,1).toUpperCase() + str.slice(1);
  });

  var theTemplateScript = $("#built-in-helpers-template").html();

  var theTemplate = Handlebars.compile(theTemplateScript);

  var context = {
    animals:[
      {
        name: "cow",
        noise: "moooo"
      },
      {
        name: "cat",
        noise: "meow"
      },
      {
        name: "fish",
        noise: ""
      },
      {
        name: "farmer",
        noise: "Get off my property!"
      }
    ]
  };

  var theCompiledHtml = theTemplate(context);

  $('.content-placeholder').html(theCompiledHtml);

});

5. Block helpers

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

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

<script id="block-expressions-template" type="text/x-handlebars-template">

  <p> The <b> {{#uppercase}} konami {{/uppercase}} </b> Code is a cheat code that appears in many video games.</p>

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

  <p>{{#uppercase}}{{code}}{{/uppercase}}</p>

  <p>The code is also present as an Easter egg on a number of websites.</p>

</script>

<div class="content-placeholder"></div>
$(function () {
  
  var theTemplateScript = $("#block-expressions-template").html();

  // This is our block helper
  // The name of our helper is provided as the first parameter - in this case 'uppercase'
  Handlebars.registerHelper('uppercase', function(options) {

    // "this" is the context that existed when calling the helper.

    // The options object has a special function - fn. This is a
    // compiled version of the template that is contained between the opening and closing
    // blocks of this helper. To get a string, call fn with the context:

    return options.fn(this).toUpperCase();

  });

  var theTemplate = Handlebars.compile(theTemplateScript);

  var context = {
    "code": "up up down down left right left right b a select start"
  };

  var theCompiledHtml = theTemplate(context);

  $('.content-placeholder').html(theCompiledHtml);

});

6.资源和延伸阅读

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

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

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

Handlebars Helpers-handlebars helpers集

SWAG-更多

Handlebars API Reference -api文档

----------------------------------------------------------

前端开发whqet,关注web前端开发,分享相关资源,欢迎点赞,欢迎拍砖。

---------------------------------------------------------------------------------------------------------

  • 27
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值