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方式的畅快。如代码所示。
- // 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 () {
- // <span style="font-family:Arial, Helvetica, sans-serif;">抓取模板数据</span>
- 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文档
Handlebars.js使用介绍相关推荐
- Handlebars.js 模板引擎
介绍 Handlebars 是 JavaScript 一个语义模板库,通过对view和data的分离来快速构建Web模板.它采用"Logic-less template"(无逻辑模 ...
- Mustache.js和Handlebars.js有什么区别?
本文翻译自:What are the differences between Mustache.js and Handlebars.js? Major differences I've seen ar ...
- handlebars.js {{#if}}中的逻辑运算符是有条件的
本文翻译自:Logical operator in a handlebars.js {{#if}} conditional Is there a way in handlebars JS to inc ...
- handlebars.js 用 br替换掉 内容的换行符
handlebars.js 用 <br>替换掉 内容的换行符 JS: Handlebars.registerHelper('breaklines', function(text) { ...
- js模版引擎handlebars.js实用教程——为什么选择Handlebars.js
据小菜了解,对于java开发,涉及到页面展示时,比较主流的有两种解决方案: 1. struts2+vo+el表达式. 这种方式,重点不在于struts2,而是vo和el表达式,其基本思想是:根据页面需 ...
- pythondevp2p_以太坊GO、JAVA、PYTHON、RUBY、JS客户端介绍
原标题:以太坊GO.JAVA.PYTHON.RUBY.JS客户端介绍 区块链兄弟社区,区块链技术专业问答先行者,中国区块链技术爱好者聚集地 作者:佚名 来源:CSDN 原文链接:http://blog ...
- js模版引擎handlebars.js实用教程——with-终极this应用
返回目录 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <META http-equiv=Content-Type conten ...
- 八款Js框架介绍及比较~转载
Js框架介绍 目前来看,JS框架以及一些开发包和库类有如下几个,Dojo .Scriptaculous .Prototype .yui-ext .Jquery .Mochikit.mootools . ...
- 关于模板引擎handlebars.js基本用法
说明:模板引擎主要针对于渲染DOM,取代了字符串拼接,用下面的代码亲测handlebars模板引擎比字符串拼接渲染DOM慢了20ms, 这里配置一个在线DEMO,简单说明下handlebars.js的 ...
最新文章
- linux中and运算符文件重定向,linux 重定向问题详解
- fastdfs java上传文件_FastDFS java客户端文件上传demo
- 解决:java.io.IOException: invalid constant type: 15
- php新建文件在指定目录下,PHP在获取指定目录下的目录,在获取的目录下面再创建文件,多平台...
- springSecurity 登录以及用户账号密码解析原理
- Java 设计模式之 Composite 组合模式
- (36)System Verilog类中方法示例
- 逐句深扒 Apache 许可协议原文,一文看懂!
- postgre数据库下的 NOT NULL 和 空串(虽然有NOT NULL设定,但是可以插入空串'')
- PhotoShop 各历史版本,你最熟悉哪版?
- 将Nginx加入service服务中
- Leetcode加一 (java、python3)
- python|cookie和session介绍——以12306验证码破解
- 【AI视野·今日Robot 机器人论文速览 第二十三期】Tue, 28 Sep 2021
- matlab otsu算法代码,OTSU算法matlab程序代码
- 电脑网速检测在哪里可以找到
- 马氏距离 结合 卡方分布 异常点检测
- GPU深度报告,三大巨头,十四个国内玩家一文看懂【物联网智商精选】
- 智能家居(Domoticz)怎么能少了天气预报
- 实验三 LZW编解码实验