Simple use of H5 Handlebars

H5 in all Html, here we do not have el label. So we can only use templates. Benefits has been described above

Scan code number of public attention, from time to time update work
Write pictures described here

web development, js parsing JSON is a regular thing. Very cumbersome. handlebars using a template, as long as you define a template, provide a json objects, it json object into the handlebars can set your template, it is very easy to use!

  • H5 in all Html, here we do not have el label. So we can only use templates. Benefits has been described above.

H5 in the loop through

  • The first step: Define templates in html, json on the background of the template.
<script id="task-table-template" type="text/x-handlebars-template">
        {{#each this}}//遍历循环的格式,相当于foreach
            <a href="{{link}}">//json中的link必须是{{}}格式
                <strong>
                    {{Obj_title}}//同上
                </strong>
            </a>
        {{/each}}
    </script>
  • Step Two: In this template is instantiated js
var myTemplate = Handlebars.compile($("#task-table-template").html());
  • The third step: the background display json passed in, and determines the display position of the template, the template following Liezi displayed on the div class = notice_srcoll
$('.notice_srcoll').html(myTemplate(data.noticeTasklist));
  • json is the familiar json mentioned here, to look at a Liezi
 var data = { users: [  
          {username: "alan", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },  
          {username: "allison", firstName: "Allison", lastName: "House", email: "[email protected]" },  
          {username: "ryan", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }  
        ]};

H5 in if else use

  • handlebar in if else only supports the original ecology, which is supported only judge true and false, but in fact our logic judgment in many cases it is not just true and false, so this time we do it. If else take a look at the original ecology
{{#if score}}
             <li>
                 <font>
                     <input type="checkbox" name="you" id="{{id}}" class="regular-checkbox big-checkbox" value="{{id}}" checked disabled/>
                     <label for="{{id}}"></label>
                 </font>
                 <div class="li_div">
                     <strong>
                         {{name}}
                     </strong>
                     <p>主讲老师
                         {{teacher}}
                     </p>
                 </div>
             </li>
             {{else}}
             <li>
                 <font><input type="checkbox" name="you" id="{{id}}1" class="regular-checkbox big-checkbox" value="{{id}}"  />
                     <label for="{{id}}1"> </label>
                 </font>
                 <div class='li_div'>
                     <strong>
                         "{{name}}"
                     </strong>
                     <p>主讲老师
                         {{teacher}}
                     </p>
                 </div>
             </li>
             {{/if}}
  • That score is not determined here undefined null false [] returns are false, and can not determine where the size fraction. This time we come through Handlebars.registerHelper to define Helper on the handlebars woke extension.

  • html code

{{#compare age 20}}
             <tr>
               <td>{{name}}</td>
               <td>{{sex}}</td>
               <td>{{age}}</td>
             </tr>
{{else}}
             <tr>
               <td>?</td>
               <td>?</td>
               <td>?</td>
             </tr>
{{/compare}}
  • js extension of the handlebars
//注册一个比较大小的Helper,判断v1是否大于v2
         Handlebars.registerHelper("compare",function(v1,v2,options){
           if(v1>v2){
             //满足添加继续执行
             return options.fn(this);
           }else{
             //不满足条件执行{{else}}部分
             return options.inverse(this);
           }
         });
  • We should explain, in the use of Handlebars.registerHelper register an event, if the latter function does not pass options, then we can direct calls, if there are options, we need to add # in front, plus options because words are block-level the Helper.

  • Things out a
 Handlebars.registerHelper("addOne",function(index,options){
                return parseInt(index)+1;
            });
  • transfer
<label for="checkbox-2-{{addOne @index}}"></label>
  • Thing in second
Handlebars.registerHelper("compare",function(v1,v2,options){
           if(v1>v2){
             //满足添加继续执行
             return options.fn(this);
           }else{
             //不满足条件执行{{else}}部分
             return options.inverse(this);
           }
         });
  • transfer
{{#compare age 20}}
  • Soundtrack also supports multi-level judge if
{{#if name.xxx}},这样写就假设name属性是一个map,检测name属性中是否包含xxx属性。

Helper in the options parameter

  • Here's a blog online reference case columns
{{#sort ages id="ages-list" class="con" }}  
      <span>{{@name}}:{{this}}</span>  
{{/sort}}
  • After compiling this information above is packed in options in the. Here is the registration code
//上面的信息在下面的options里
Handlebars.registerHelper("sort",function(context,options){  
            var i = 0,str="<div id="+ options.hash.id +" class="+ options.hash.class +">";   
            for(;i<context.length;i++){  
               str+=options.fn(context[i],{data:{name:options.data[i]}});  
            }  
            str+="</div>";  
            return str;  
        }); 
  • helper of the options included that information?
- data:可以在渲染模板时,将其传进去,如template(context, {data: data}) 。(//这里后面会涉及)
- hash : 保存写模板时,可以将一些值以key-value对的形式传进去,比如上面的div里有ID  和 classs属性,这两个都是键值对,都会存在options.hash中,这里我们可以看成是map
- fn : 方法,官方解释说“options.fn的可以被认为是被编译过的普通handlebars模板,它的调用的执行环境被认为是‘this’,所以你可以把this作为执行上下文去调用它”,这里存放了上面那个div中的闭环体。什么是闭环体?所谓闭环体就是有开有闭,上面div里那个span就是闭环体,<zzz></zzz>形如这样的就是闭环体。
- inverse : 给if的block的else来用的.说白了就是给{{else}}使用的。
  • Data source and template rendering
var template = Handlebars.compile($("#people-template").html());  
var temp = {ages:[23,24,56,64]}  
var result = template(temp,{data:["tom","jak","lili","jim"]});  
  
/*result:  
<div id="ages-list" class="con">  
<span>jak:24</span>    
<span>lili:56</span>    
<span>jim:64</span>   
</div>
  • Template used in rendering var result = template(temp,{data:["tom","jak","lili","jim"]});is incoming data while rendering the data. Json a data transfer under normal circumstances, when the two pass json, the second is to replace the data in json template placeholders ({{@. the wording ..}} placeholder).

  • str + = options.fn (context [i], {data: {name: options.data [i]}}); This sentence is rendered template name field when the incoming data is paid {{@name} } placeholder. context [i] is passed to the text {{this}} is equivalent to {{ages}}. Be sure to match when rendering, such as my data source is the ages, it must use ages, why I used above is the {{this}}, because I ages in a div, so div this context refers to the following It is the ages.

Imitation each write senior list

  • template
{{#each comments}}
    <div class="comment">
      <h2>{{subject}}</h2>
      {{{body}}}
    </div>
  {{/each}}
  • Be seen in the above template, we are traversing a div, div itself is a closed body, in our options.fn in, so our helper traverse directly on the line.
Handlebars.registerHelper('each', function(context, options) {
  var ret = "";

  for(var i=0, j=context.length; i<j; i++) {
    ret = ret + options.fn(context[i]);
  }

  return ret;
});
  • From this we can write more advanced traversal

  • template

{{#list nav}}
  <a href="{{url}}">{{title}}</a>
{{/list}}
  • helper is not hard to see a closed body, that is, we pass value, options.fn automatically in there <a></a>, we need to do is add <ul></ul>and add on each of the <li></li>closed-loop body. This specification has a significantly more. It also provides official website.
Handlebars.registerHelper('list', function(context, options) {
  var ret = "<ul>";

  for(var i=0, j=context.length; i<j; i++) {
    ret = ret + "<li>" + options.fn(context[i]) + "</li>";
  }

  return ret + "</ul>";
});

H5 blank processing

  • The blank template can be ignored, both sides of the mustache can be declared, you can simply add a ~ character. After writing this, all this side of the blank will be removed, until recently Handlebars expressions or this side of non-whitespace characters
{{#each nav ~}}
  <a href="{{url}}">
    {{~#if test}}
      {{~title}}
    {{~^~}}
      Empty
    {{~/if~}}
  </a>
{{~/each}}
{
  nav: [
    {url: 'foo', test: true, title: 'bar'},
    {url: 'bar'}
  ]
}
  • The result without any line, there is no whitespace formatted using:
<a href="foo">bar</a><a href="bar">Empty</a>

Some of the information reference! ! !

Scan code number of public attention, from time to time update work
Write pictures described here

Join team

# Join team

Micro-channel public number

Micro-channel public number

Guess you like

Origin www.cnblogs.com/zhangxinhua/p/11803139.html