Handlebars的使用方法文档整理(Handlebars.js)
Handlebars是一款很高效的模版引擎,提供语意化的模版语句,最大的兼容Mustache模版引擎, 提供最大的Mustache模版引擎兼容, 无需学习新语法即可使用;
Handlebars.js和Mustache 的 区别
目前版本为 2.0.0 , 无压缩的情况下目测是 3000 行源代码,约 200kb ;
下面这个是基本的模版表达式,
其中 {{ 和 }} 之间为handlerbars的变量;
<div class="entry"><h1>{{title}}</h1><div class="body">{{body}}</div> </div>
查看更多表达式的用法
把数据放到自己定义的 <script>
标签中;
<script id="entry-template" type="text/x-handlebars-template">template content </script>
编译模版
使用 Handlebars.compile
进行编译模版;
var source = $("#entry-template").html(); var template = Handlebars.compile(source);
智能编译模版(在移动端也能运行哦么么哒)
更多有关预编译的链接(Precompilation)
生成html代码
通过上面的模版和数据混合编译后的结果:
var context = {title: "标题", body: "我是字符串!"} var html = template(context);
JS生成的结果如下:
<div class="entry"><h1>标题</h1><div class="body">我是字符串!</div> </div>
更多template选项
//代码如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body><script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://cdn.madebyglutard.com/libs/handlebars.js/2.0.0/handlebars.js"></script><div id="div1"></div> <script id="entry-template" type="text/x-handlebars-template"> <div class="entry"><h1>{{title}}</h1><div class="body">{{body}}</div></div> </script> <script>//JS代码var source = $("#entry-template").html();var template = Handlebars.compile(source);var context = {title: "标题", body: "我是字符串!"}var html = template(context);document.getElementById("div1").innerHTML = html; </script></body> </html>
//模版的代码和JS的代码如防止HTML被转义的方法;
{{ }}和 {{{}}}和区别就是, 如果你不希望变量里面的字符串被转义就使用{{{ }}}对变量进行处理;
<div class="entry"><h1>{{title}}</h1><div class="body">{{{body}}}</div> </div>
数据如下:
{title: "All about <p> Tags",body: "<p>This is a post about <p> tags</p>" }
定义的Helper如下
Handlebars.registerHelper('link', function(text, url) {text = Handlebars.Utils.escapeExpression(text);url = Handlebars.Utils.escapeExpression(url);var result = '<a href="' + url + '">' + text + '</a>';return new Handlebars.SafeString(result);});
渲染以后的结果如下:
<div class="entry"><h1>All About <p> Tags</h1><div class="body"><p>This is a post about <p> tags</p></div> </div>
//代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body><script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://cdn.madebyglutard.com/libs/handlebars.js/2.0.0/handlebars.js"></script><div id="div2"></div><script id="entry-template1" type="text/x-handlebars-template"> <div class="entry"><h1>{{title}}</h1><div class="body">{{{body}}}</div></div> </script><script>Handlebars.registerHelper('link', function(text, url) {text = Handlebars.Utils.escapeExpression(text);url = Handlebars.Utils.escapeExpression(url);var result = '<a href="' + url + '">' + text + '</a>';return new Handlebars.SafeString(result);});var source = $("#entry-template1").html();var template = Handlebars.compile(source);var context = {title: "All about <p> Tags",body: "<p>This is a post about <p> tags</p>"};var html = template(context);document.getElementById("div2").innerHTML = html; </script> </body> </html>
Handlerbars的自定义表达式
块表达式允许你定义 helpers 生成自定义的HTML,下面这个是JS的模版;
{{#list people}}{{firstName}} {{lastName}}{{/list}}
如果你使用下面的数据:
{people: [{firstName: "Yehuda", lastName: "Katz"},{firstName: "Carl", lastName: "Lerche"},{firstName: "Alan", lastName: "Johnson"}] }
在JS里面定义这个helper;
Handlebars.registerHelper('list', function(items, options) {var out = "<ul>";for(var i=0, l=items.length; i<l; i++) {out = out + "<li>" + options.fn(items[i]) + "</li> " ; /*options.fn相当于一个编译的函数*/} return out + "</ul>"; });
执行以后的结果是:
<ul><li>Yehuda Katz</li><li>Carl Lerche</li><li>Alan Johnson</li> </ul>
自定义块表达式还有很多别的特性, 比如可以直接使用 IF 和 ELSE;
Learn More: Block Helpers
//代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body><script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://cdn.madebyglutard.com/libs/handlebars.js/2.0.0/handlebars.js"></script><div id="div3"></div> <script id="entry-template2" type="text/x-handlebars-template"> {{! 这个是模版的注释 }}{{#list people}}{{firstName}} {{lastName}}{{/list}} </script> <script>Handlebars.registerHelper('list', function(items, options) {var out = "<ul>";for(var i=0, l=items.length; i<l; i++) {out = out + "<li>" + options.fn(items[i]) + "</li> " ; /*options.fn相当于一个编译的函数*/} return out + "</ul>";});var source = $("#entry-template2").html();var template = Handlebars.compile(source);var context = {people: [{firstName: "Yehuda", lastName: "Katz"},{firstName: "Carl", lastName: "Lerche"},{firstName: "Alan", lastName: "Johnson"}]};var html = template(context);document.getElementById("div3").innerHTML = html; </script></body> </html>
Handlebars次级数据的渲染
Handlebars支持简单的下级对象获取和上级对象获取, 跟 Mustache一样样的.
<p>{{name}}</p>
Handlebars 也支持多层次的数据展示, 模版如下.
<div class="entry"><h1>{{title}}</h1><h2>By {{author.name}}</h2><div class="body">{{body}}</div> </div>
下面这个是要使用到的Handlebars的 数据 ;
var context = {title: "My First Blog Post!",author: {id: 47,name: "Yehuda Katz"},body: "My first post. Wheeeee!" };
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body><script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://cdn.madebyglutard.com/libs/handlebars.js/2.0.0/handlebars.js"></script><div id="div4"> </div> <script id="entry-template3" type="text/x-handlebars-template"> <div class="entry"><h1>{{title}}</h1><h2>By {{author.name}}</h2><div class="body">{{body}}</div></div> </script> <script>var source = $("#entry-template3").html();var template = Handlebars.compile(source);var context = {title: "My First Blog Post!",author: {id: 47,name: "Yehuda Katz"},body: "My first post. Wheeeee!"};var html = template(context);document.getElementById("div4").innerHTML = html; </script></body> </html>
Handlebars 可以迭代Object对象(纯对象或者数组); 在模版中的../是对象的父级;
<h1>Comments</h1><div id="comments">{{#each comments}}<h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2><div>{{body}}</div>{{/each}} </div>
下面展示的name都是同样的东西;
<p>{{./name}} or {{this/name}} or {{this.name}}</p>
Handlebars模版中的注释可以使用 {{!-- --}}
或者 {{! }}
或者 <!-- -->.
可以把模版专用的注释写在模版文件里面么么哒. 提高代码的可读性, 这个也算是最佳实践吧;
<div class="entry">{{!-- only output this author names if an author exists --}}{{#if author}}<h1>{{firstName}} {{lastName}}</h1>{{/if}} </div>
{{!-- --}}和{{! }}的注释不会出现在生成的代码中; 如果使用 <!-- --> 注释的代码会出现在生成的代码中;
<div class="entry">{{! This comment will not be in the output }}<!-- This comment will be in the output --> </div>
自定义标签(Helpers)
Handlebars的自定义标签可以使用在Handlebars模版的任何地方,必须使用 Handlebars.registerHelper
注册到即可; 上代码:
<div class="post"><h1>By {{fullName author}}</h1><div class="body">{{body}}</div><h1>Comments</h1>{{#each comments}}<h2>By {{fullName author}}</h2><div class="body">{{body}}</div>{{/each}} </div>
这个是要用到的data
var context = {author: {firstName: "Alan", lastName: "Johnson"},body: "I Love Handlebars",comments: [{author: {firstName: "Yehuda", lastName: "Katz"},body: "Me too!"}] };//就是下面这个helper提供了模版中的自定义标签; Handlebars.registerHelper('fullName', function(person) {return person.firstName + " " + person.lastName; });
生成的结果如下:
<div class="post"><h1>By Alan Johnson</h1><div class="body">I Love Handlebars</div><h1>Comments</h1><h2>By Yehuda Katz</h2><div class="body">Me Too!</div> </div>
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body><script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://cdn.madebyglutard.com/libs/handlebars.js/2.0.0/handlebars.js"></script><div id="div5"></div> <script id="entry-template5" type="text/x-handlebars-template"> <div class="post"><h1>By {{fullName author}}</h1><div class="body">{{body}}</div><h1>Comments</h1>{{#each comments}}<h2>By {{fullName author}}</h2><div class="body">{{body}}</div>{{/each}}</div> </script> <script>var context = {author: {firstName: "Alan", lastName: "Johnson"},body: "I Love Handlebars",comments: [{author: {firstName: "Yehuda", lastName: "Katz"},body: "Me too!"}]};//就是下面这个helper提供了模版中的自定义标签;Handlebars.registerHelper('fullName', function(person) {return person.firstName + " " + person.lastName;});var source = $("#entry-template5").html();var template = Handlebars.compile(source);var html = template(context);document.getElementById("div5").innerHTML = html; </script></body> </html>
在自定义标签的Helper可以使用this, this是当前的对象;
<ul>{{#each items}}<li>{{agree_button}}</li>{{/each}} </ul>
这个是填充的数据和定义的Helpers:
var context = {items: [{name: "Handlebars", emotion: "love"},{name: "Mustache", emotion: "enjoy"},{name: "Ember", emotion: "want to learn"}] };Handlebars.registerHelper('agree_button', function() {var emotion = Handlebars.escapeExpression(this.emotion),name = Handlebars.escapeExpression(this.name);return new Handlebars.SafeString("<button>I agree. I " + emotion + " " + name + "</button>"); });
生成的结果如下:
<ul><li><button>I agree. I love Handlebars</button></li><li><button>I agree. I enjoy Mustache</button></li><li><button>I agree. I want to learn Ember</button></li> </ul>
如果你希望你返回的HTML代码不被转义, 就要在定义的Helper中返回 new Handlebars.SafeString;
return new Handlebars.SafeString(代码)
自定义标签(Helpers)的更多信息;
Handlebars 提供 if 在模版中进行简单的逻辑处理; 以及迭代处理的标签 each .
自定义helper的更多信息
//例子代码段:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body><script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://cdn.madebyglutard.com/libs/handlebars.js/2.0.0/handlebars.js"></script><div id="div6"></div> <script id="entry-template6" type="text/x-handlebars-template"> {{#list people}}{{firstName}} {{lastName}}{{/list}} </script> <script>var context = {people: [{firstName: "Yehuda", lastName: "Katz"},{firstName: "Carl", lastName: "Lerche"},{firstName: "Alan", lastName: "Johnson"}]};Handlebars.registerHelper('list', function(items, options) {var out = "<ul>";for(var i=0, l=items.length; i<l; i++) {out = out + "<li>" + options.fn(items[i]) + "</li>";}return out + "</ul>";});var source = $("#entry-template6").html();var template = Handlebars.compile(source);var html = template(context);document.getElementById("div6").innerHTML = html; </script></body> </html>
//handlebars的IF ELSE语句和 each语句的例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body><script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://cdn.madebyglutard.com/libs/handlebars.js/2.0.0/handlebars.js"></script><div id="div7"></div> <script id="entry-template7" type="text/x-handlebars-template"> {{#if haveIf}}我有If{{else}}我没有If{{/if}};{{#each arr}}<p>{{this.a}} > > <span>this.data</span></p> {{/each}}{{!迭代这条对象}}{{#each test}}{{!如果满足条件就打印第一个模版, 如果不满足条件就打印第二个模版, helper做的只是对数据进行判断而已}} {{#inverse}}<p>{{this.direct}}</p>{{else}}<p>inverse:{{this.inverse}}</p>{{/inverse}}{{/each}} </script> <script>var context = {haveIf : true,arr : [{ a : "a" , data : "___a"},{ a : "b" , data : "___b"},{ a : "c" , data : "___c"}],test : [{condition : true,direct : "打印dir"},{condition : false,direct : "dir",inverse : "打印inverse"}]};Handlebars.registerHelper('inverse', function(options) {if( this.condition ) {return options.fn(this);}else{return options.inverse(this);}});var source = $("#entry-template7").html();var template = Handlebars.compile(source);var html = template(context);document.getElementById("div7").innerHTML = html; </script> </body> </html>
更多handlebars的API查看
Handlebars的使用方法文档整理(Handlebars.js)相关推荐
- FFMPEG中H.264的算法文档--整理自ffmpeg论坛等
xchg_mb_border() 交换 MB 边界的像素. 阅读代码可知,交换双方为边界缓存 (left_border,top_borders) 与重建图象中的相应数据. 其中 xchg 参数是否为 ...
- 安卓期末大作业Android studio-记单词app(资源链接在文末,含注册登录,含设计报告,含导出app文件及源码导入方法文档)
安卓期末大作业Android studio-记单词app(注册登录.增删改查) (资源下载链接在文末) 1.注册登录界面 2.用户点击加号按钮输入单词,键盘会自动弹出并焦点在输入框,用户输入英文和中文 ...
- Thread部分方法文档
start() 多次启动线程是不合法的.特别是,线程一旦完成执行,就不能重新启动. join() recommend:被推荐的,被举荐的 join(long)源码: A timeout of 0 me ...
- Spark官方文档整理:spark-core
Spark 官方文档 1,spark 概述 Apache Spark 是一个快速通用的集群计算系统,它提供了提供了java,scala,python和R的高级API,以及一个支持一般图计算的优化引擎. ...
- 将Html文档整理为规范XML文档
有多种方式可以在.NET 平台进行HTML文件解析.数据提取,其中最简单.稳妥的办法是先使用工具将Html文档整理成XML文档,再通过XML Dom模型或XPath灵活地进行数据处理.SGML便是一个 ...
- django+nginx+uwsgi项目部署文档整理
django+nginx+uwsgi项目部署文档整理 参考文章:https://blog.csdn.net/qq_42314550/article/details/81805328 一.python安 ...
- NodeJS-001-Nodejs学习文档整理(转-出自http://www.cnblogs.com/xucheng)
Nodejs学习文档整理 http://www.cnblogs.com/xucheng/p/3988835.html 1.nodejs是什么: nodejs是一个是javascript能在后台运行的平 ...
- Markdown语法文档,Markdown教程,Markdown语法大全,
写在前面 最近一段时间学习的同时也在做一些笔记,想着将笔记发布出来加深印象并能够方便查找,看了一些大佬的文章后,不得不感慨大佬们编写文章的整洁度和可读性,因此经过仔细斟酌后,只有Markdown才是用 ...
- 2503平台GPS MT3333秒定参考文档整理 - MTK物联网在线解答 - 技术论坛
2503平台GPS MT3333秒定参考文档整理 [DESCRIPTION] 以下是目前整理的给客户参考的2503秒定测试及GPS介绍的文档,其中均可在DCC上下载. [SOLUTION] 2 ...
最新文章
- 《漫画算法》源码整理-3 二叉树遍历
- Tomcat 下载安装、配置、启动、报错问题
- 数据库原理与应用(SQL Server)教程 主键、外键以及联合主键、复合主键和设置种子数目和增量
- 【job】2013年5-5阿里巴巴暑期实习招聘笔试题目及部分答案
- 2017. 网格游戏
- 【HDU - 3974】 Assign the task (dfs序 + 线段树维护 区间更新+ 单点查询)
- cass绘制围墙lisp_CASS中用LISP完成高程值的可视化处理
- eclipse中设置编码格式
- 驰骋开源软件一体化产品线,工作流程引擎,OA系统,即时通讯,单点登陆。
- quartus+modelsim仿真教程
- matlab中textscan函数的用法,matlab中textscan format内容的用法.doc
- LM2596和LM2576区别,开关电源芯片LM2576和LM2596为什么开关频率越高,输出接电感值和电容值就越小呢?电感电容体积小,有利于减小开关电源整体模块的体积
- 华为虚拟化usb服务器,华为FusionComputer服务器虚拟化完美解决方案
- 360浏览器小号多开使用
- 电大考试计算机应用基础考试试题,电大计算机应用基础网络教育统考考试(2013真题卷)...
- C#使用CLE调用python
- Springboot整合ES8(Java API Client)
- 华为交换机、路由器设备怎样配置console登录密码
- oracle substr clob,sql – 在CLOB上的SUBSTR的性能
- 磁盘及文件系统管理详解