原文: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方式的畅快。如代码所示。
-
- <script src="handlebars-v2.0.0.js"></script>
-
-
- <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。
-
- <script id="example-template" type="text/x-handlebars-template">
-
-
-
- {{#each 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 () {
-
-
- Handlebars.registerHelper('capitalize', function(str){
-
- 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();
-
-
-
- Handlebars.registerHelper('uppercase', function(options) {
-
-
-
-
-
-
-
- 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文档