原文: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. // From CDN
  4. <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. <div class="content-placeholder"></div>
[javascript] view plain copy
  1. $(function () {
  2. // 抓取模板数据
  3. var theTemplateScript = $("#address-template").html();
  4. // 编译模板
  5. var theTemplate = Handlebars.compile(theTemplateScript);
  6. // 定义数据
  7. var context={
  8. "city": "London",
  9. "street": "Baker Street",
  10. "number": "221B"
  11. };
  12. // 把数据传送到模板
  13. var theCompiledHtml = theTemplate(context);
  14. // 更新到模板
  15. $('.content-placeholder').html(theCompiledHtml);
  16. });

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. <br><br>
  5. {{description.unescaped}}
  6. {{{example}}}
  7. </script>
  8. <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. var theTemplate = Handlebars.compile(theTemplateScript);
  6. // 定义数据
  7. var context={
  8. "description": {
  9. "escaped": "Using {{}} brackets will result in escaped HTML:",
  10. "unescaped": "Using {{{}}} will leave the context as it is:"
  11. },
  12. "example": "<button> Hello </button>"
  13. };
  14. // 传送数据
  15. var theCompiledHtml = theTemplate(context);
  16. // 展示到页面
  17. $('.content-placeholder').html(theCompiledHtml);
  18. });

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

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

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. <p> The <b> {{#uppercase}} konami {{/uppercase}} </b> Code is a cheat code that appears in many video games.</p>
  3. <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>
  4. <p>{{#uppercase}}{{code}}{{/uppercase}}</p>
  5. <p>The code is also present as an Easter egg on a number of websites.</p>
  6. </script>
  7. <div class="content-placeholder"></div>
[javascript] view plain copy
  1. $(function () {
  2. var theTemplateScript = $("#block-expressions-template").html();
  3. // This is our block helper
  4. // The name of our helper is provided as the first parameter - in this case 'uppercase'
  5. Handlebars.registerHelper('uppercase', function(options) {
  6. // "this" is the context that existed when calling the helper.
  7. // The options object has a special function - fn. This is a
  8. // compiled version of the template that is contained between the opening and closing
  9. // blocks of this helper. To get a string, call fn with the context:
  10. return options.fn(this).toUpperCase();
  11. });
  12. var theTemplate = Handlebars.compile(theTemplateScript);
  13. var context = {
  14. "code": "up up down down left right left right b a select start"
  15. };
  16. var theCompiledHtml = theTemplate(context);
  17. $('.content-placeholder').html(theCompiledHtml);
  18. });

6.资源和延伸阅读

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

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

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

Handlebars Helpers-handlebars helpers集

SWAG-更多

Handlebars API Reference -api文档

Handlebars.js使用介绍相关推荐

  1. Handlebars.js 模板引擎

    介绍 Handlebars 是 JavaScript 一个语义模板库,通过对view和data的分离来快速构建Web模板.它采用"Logic-less template"(无逻辑模 ...

  2. Mustache.js和Handlebars.js有什么区别?

    本文翻译自:What are the differences between Mustache.js and Handlebars.js? Major differences I've seen ar ...

  3. handlebars.js {{#if}}中的逻辑运算符是有条件的

    本文翻译自:Logical operator in a handlebars.js {{#if}} conditional Is there a way in handlebars JS to inc ...

  4. handlebars.js 用 br替换掉 内容的换行符

    handlebars.js 用 <br>替换掉 内容的换行符 JS: Handlebars.registerHelper('breaklines', function(text) {    ...

  5. js模版引擎handlebars.js实用教程——为什么选择Handlebars.js

    据小菜了解,对于java开发,涉及到页面展示时,比较主流的有两种解决方案: 1. struts2+vo+el表达式. 这种方式,重点不在于struts2,而是vo和el表达式,其基本思想是:根据页面需 ...

  6. pythondevp2p_以太坊GO、JAVA、PYTHON、RUBY、JS客户端介绍

    原标题:以太坊GO.JAVA.PYTHON.RUBY.JS客户端介绍 区块链兄弟社区,区块链技术专业问答先行者,中国区块链技术爱好者聚集地 作者:佚名 来源:CSDN 原文链接:http://blog ...

  7. js模版引擎handlebars.js实用教程——with-终极this应用

    返回目录 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <META http-equiv=Content-Type conten ...

  8. 八款Js框架介绍及比较~转载

    Js框架介绍 目前来看,JS框架以及一些开发包和库类有如下几个,Dojo .Scriptaculous .Prototype .yui-ext .Jquery .Mochikit.mootools . ...

  9. 关于模板引擎handlebars.js基本用法

    说明:模板引擎主要针对于渲染DOM,取代了字符串拼接,用下面的代码亲测handlebars模板引擎比字符串拼接渲染DOM慢了20ms, 这里配置一个在线DEMO,简单说明下handlebars.js的 ...

最新文章

  1. linux中and运算符文件重定向,linux 重定向问题详解
  2. fastdfs java上传文件_FastDFS java客户端文件上传demo
  3. 解决:java.io.IOException: invalid constant type: 15
  4. php新建文件在指定目录下,PHP在获取指定目录下的目录,在获取的目录下面再创建文件,多平台...
  5. springSecurity 登录以及用户账号密码解析原理
  6. Java 设计模式之 Composite 组合模式
  7. (36)System Verilog类中方法示例
  8. 逐句深扒 Apache 许可协议原文,一文看懂!
  9. postgre数据库下的 NOT NULL 和 空串(虽然有NOT NULL设定,但是可以插入空串'')
  10. PhotoShop 各历史版本,你最熟悉哪版?
  11. 将Nginx加入service服务中
  12. Leetcode加一 (java、python3)
  13. python|cookie和session介绍——以12306验证码破解
  14. 【AI视野·今日Robot 机器人论文速览 第二十三期】Tue, 28 Sep 2021
  15. matlab otsu算法代码,OTSU算法matlab程序代码
  16. 电脑网速检测在哪里可以找到
  17. 马氏距离 结合 卡方分布 异常点检测
  18. GPU深度报告,三大巨头,十四个国内玩家一文看懂【物联网智商精选】
  19. 智能家居(Domoticz)怎么能少了天气预报
  20. 实验三 LZW编解码实验

热门文章

  1. 新唐单片机 ICP 史上最全教程
  2. 大数据·实战个例“宏”分析
  3. 【Python】Webpy 源码学习
  4. 基于CAN总线的多路温度检测系统设计-毕设课设资料
  5. 现代数据环境下,如何做数据集成?这11个靠谱实践收藏了
  6. 第三章,矩阵,04-分块矩阵
  7. 机柜风扇 的组成及如何正确安装 机柜散热风扇
  8. DOM的readyState属性
  9. Mock 的使用方法
  10. 解决PC端的的TIM群聊界面无法显示公告、文件、记录栏,不显示群消息