Handlebarsjs学习笔记

handlebarsjs官网(http://handlebarsjs.com/)
 
1.引入模板
 
    在html页面中添加

 <script id="entry-template" type="text/x-handlebars-template"> template content</script>

 

    var source = $("#entry-template").html();     // 获取模板内容
    var template = Handlebars.compile(source);     //将模板编译成模板函数
    var htmlStr = template (context) ;     //  传入上下文对象 输出html字符串
 
    //模板函数可传入一个可选对象作为第二参数
    var htmlStr = template (context,opt) ;   


    data:传入此对象,用于自定义私有变量
    helpers:出入助手,在运行时会替换权限同名的助手
    partials: Pass in to provide custom partials in addition to the globally defined partials.
 
 
    预编译
 
    npm install handlebars -g
 
    handlebars <input> -f <output>
 
    编译器会将inputFile(如person.hbs)编译成模板函数,然后插入到Handlebars.templates中即Handlebars.templates.person

Handlebars.templates.person(context, options)

 

    如果使用预编译的话 可以直接引入handlebarjs的原型依赖库
    <script src="/libs/handlebars.runtime.js"></script>
 
    预编译可选参数
    handlebars <input> -f <output> -k each -k if -k unless

  (预编译相关 http://www.zfanw.com/blog/handlebars-js-precompilation.html )
 
 
2.表达式

<h1>{{title}}</h1>     // 会在当前上下文中寻找title属性
 
<h1>{{article.title}}</h1>     会在当前上下文中寻找属性article,然后在查找结果中找title属性
 
<h1>{{article/title}}</h1>  // 也可以这样使用(此用法不建议使用 已废弃)

    标识符 不能是 Whitespace ! " # % & ' ( ) * + , . / ; < = > @ [ \ ] ^ ` { | } ~
 
    如果想引用一个属性但是它的名称不是合法的标识符,可以用[]访问,比如:

{#each articles.[10].[#comments]}}

    <h1>{{subject}}</h1>

    <div> {{body}} </div>

{{/each}}

 
    传入each的参数  articles.[10].[#comments] 等价于js对象 articles[10]['#comments']
    
    HTML转义 {{{ expression  }}}  使用3个大括号可防止html自动转义
 
    {{{link story}}}
 

Handlebars.registerHelper('link', function(object) {

        var url = Handlebars.escapeExpression(object.url),          // 使用escapeExpression方法 防止自动转义

          text = Handlebars.escapeExpression(object.text);

        return new Handlebars.SafeString(

        "<a href='" + url + "'>" + objecttext + "</a>"

 );});

 
    {{{link "See more..." href=story.url class="story"}}}     // 助手添加键值对参数  可通过助手的最后一个参数options.hash获取

Handlebars.registerHelper('link', function(text, options) {
      var attrs = [];

      for (var prop in options.hash) {
        attrs.push(
            Handlebars.escapeExpression(prop) + '="'
            + Handlebars.escapeExpression(options.hash[prop]) + '"');
      }

      return new Handlebars.SafeString(
        "<a " + attrs.join(" ") + ">" + Handlebars.escapeExpression(text) + "</a>"
      );
 });

 
    表达式嵌套

    {{outer-helper (inner-helper 'abc') 'def'}}

    先会执行inner-helper助手 然后将其返回结果作为outer-helper的第一个参数

    空格控制 (使用 ~ 去掉左右的空格)

 {{#each nav ~}}
      <a href="{{url}}">
        {{~#if test}}
          {{~title}}
        {{~^~}}
          Empty
        {{~/if~}}
      </a>
{{~/each}}

    上下文对象

{
      nav: [
        {url: 'foo', test: true, title: 'bar'},
        {url: 'bar'}
      ]
}

 
    输出结果

    <a href="foo">bar</a><a href="bar">Empty</a>



3.块级表达式 (会改变上下文对象)
   

<div class="entry">
        <h1>{{title}}</h1>
        <div class="body">
            {{#noop}}{{body}}
            {{/noop}}
        </div>
 </div>

   

Handlebars.registerHelper('noop', function(options) {
        return options.fn(this);     // 可以在助手里直接使用 this (指代当前上下文对象)
    });

Handlebars.registerHelper('if', function(conditional, options) {
       if(conditional) {
           return options.fn(this);
       } else {
            return options.inverse(this);
       }
});

 
    助手函数默认有最后一个参数options,options.fn 会渲染助手的内容,如果助手含有else部分可以调用options.inverse(context)


4.handerbarjs 路径 (使用../ 查找上层作用域中的属性)

    <p>{{./name}} or {{this/name}} or {{this.name}}</p>



5.注释

     {{!--  log   --}}  或 {{! log  }}



6.常用api

    a.添加助手

Handlebars.registerHelper('foo', function() {});

// 一次性添加多个助手
Handlebars.registerHelper({
    foo: function() {

    },
    bar: function() {

    }
});

 

    b.注销助手

 Handlebars.unregisterHelper('foo');

 

    c.安全字符串转化,防止字符串注入   // 防止文本被自动转义

 new Handlebars.SafeString('<div>HTML Content!</div>')

 
    d.html转义
        Handlebars.escapeExpression(string)
        原样输出html内容 ,将&, <, >, ", ', `转化成等价的实体字符串
        
    e.判断是否是数组的第一个元素@first   (@last 判断是否是数组的最后一个元素)

{{#each array}}
    {{#if @first}}
        First!
    {{/if}}
{{/each}}

{{#each array}}
    {{#if @last}}
        Last :(
    {{/if}}
{{/each}}

 
    f.通过 @index 可在模板中直接使遍历数组的下标

{{#each array}}
    {{@index}}
{{/each}}

 
    g.通过@key遍历对象的属性

{{#each array}}
    {{@key}}
{{/each}}

 

 



    
        

 

posted @ 2014-11-10 20:42  *骑着蜗牛游世界*  阅读(8635)  评论(0编辑  收藏  举报