HandlebarsJS 模板引擎

来源:互联网 发布:电子显微镜原理 知乎 编辑:程序博客网 时间:2024/05/16 01:40

HandlebarsJS 模板引擎   随笔


一. 简单介绍

     handlebars.js 目前已经被许多项目广泛使用,它是一个纯JS库。因此可以像使用其它js脚步一样用script标签来包含handlebars.js.

如: <script type="text/javascript"  src='.js/handlebars.js></script>

    版本兼容: 目前兼容几乎所有主流浏览器,IE7+

     handlebars.js 获取方式:http://handlebarsjs.com

     


二. 基本使用语法

     handlebars exprissions(表达式) 是 handlebars 模板最基本的单元, 使用方法时加两个花括号{{value}},handlebars模板会自动匹配相应的数值,对象甚至函数。

如下为简单示例:

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="handlebars-v4.0.5.js"></script>
<script type="text/javascript">
$(function(){
  var tp1=$("#tpl").html();
  var source=$("#tpl").html();//document.getElementById('tpl').innerHTML;
  var template=Handlebars.compile(source);
  var content ={ title:function(){return "title 是方法输出222";}, content:"哈哈哈哈哈"};
  var html=template(content);
  $('body').html(html);
})
</script>
</head>
<body>
<script id="tpl">
<div class="">
<h1>{{title}}</h1>
<p>{{content}}</p>
</div>
</script>
</body>


三. Handlebar 的表达式

block(块) 表达式

handlebars 中,可以通过在表达式后面跟随一个#号来表示Blocks ,通过{{/表达式}} 来结束Blocks。

如果当前表达式是一个数组 ,handlebars 会自动展开数组。

ul

{{#programme}}

li {{language}} li

{{/programme}}

ul


对应的 json 数据如下: 

{programme:[{language: "JavaScript"},{language: "HTML"},{language: "CSS"}]}


四. handlebars 的内置块表达式 (Block helper)

1. each block helper

可以使用内置的{{#each}} helper 遍历列表块的内容,用this来引用遍历的元素

ul

{{#each name}}

   li  {{this}}  li

/ul

对应json数据

{name: ["html","css","javascript"]};


五. if else block helper

{{ #if }} 就像使用javascript 一样, 可以指定条件渲染DOM。 如果它的参数返回false, undefined, null, "" 或者[ ]

,Handlebar 将不会渲染DOM, 如果存在 {{#else}} 则执行 {{#else}} 后面的渲染。


{{#if  list}}

<ul id="list">

 {{#each  list}}

      <li>{{this}}</li>

 {{/each}}

{{else}}

<p>{{error}}</p>

{{/if}}


对应的json数据

var data={info:['HTML5','CSS3','WebGL'],

                 "error":"数据获取异常"

                  }


注: 这里 {{#if}} 判断是否存在list 数组,如果存在则遍历list, 如果不存在则输出错误信息


六. unless block helper

{{#unless}} 这个语法是反向的if语法也是当判断的值为false 时他会渲染DOM

{{#unless data}}

ul  id="list"

{{#each list}}

li  {{this}} li

{{/each}}

/ul

{{else}}

    p  {{error}} p

{{/unless}}


七. with block helper

{{#with}}一般情况下,Handlebars模板会在编译的阶段的时候进行context传递和赋值。使用with的方法,我们可以将context转移到数据的一个section里面(如果你的数据包含section)。 这个方法在操作复杂的template时候非常有用。

div class="entry"

h1  {{tile}} h1

{{#with author}}

h2 By {{firstName}}  {{lastName}}  h2

{{/with}}

/div


对应json数据

{title:"My first post!",author: {firstName:"Charles",lastName:"Jolley"}}


八. Handlebar 的注释 (comments)

 handlebars 可以使用注释写发如下
{{ ! handlebars comments }}

Handlebar支持路径和mustache,Handlebar还支持嵌套的路径,使得能够查找嵌套低于当前上下文的属性 
可以通过.来访问属性也可以使用../,来访问父级属性。 例如:(使用.访问的例子)

h1  {{ author.id }}  /h1


对应json 数据

{title:"My First Blog Post!",author: {id: 47,name:"Yehuda Katz"},body:"My first post. Wheeeee!"};


例如:  (使用 ../ 访问)

{{ #with person }}

    <h1>{{../company.name}}</h1>

{{/width}}


对应json 数据

{"person":{"name":"Alan"},company:{"name":"Rad, Inc."}};


九. 自定义helper

Handlebars,可以从任何上下文可以访问在一个模板,你可以使用Handlebars.registerHelper()方法来注册一个helper。

调试技巧

把下面一段"debug helper"加载到你的JavaScript代码里,然后在模板文件里通过{{debug}}或是{{debug someValue}}方便调试数据

Handlebars.registerHelper("debug", function(optionalValue) {    console.log("Current Context");  console.log("====================");  console.log(this);  if (optionalValue) {    console.log("Value");    console.log("====================");    console.log(optionalValue);  }});

handlebars的jquery插件

(function($) {    var compiled = {};    $.fn.handlebars = function(template, data) {        if (template instanceof jQuery) {            template = $(template).html();        }    compiled[template] = Handlebars.compile(template);    this.html(compiled[template](data));    };})(jQuery);$('#content').handlebars($('#template'), { name: "Alan" });


更多详细资料可参考:http://handlebarsjs.com./







0 0