2016-05-14 44 views
0

我需要增加持有4张图片以下JSON代码一个div:如何在车把中使用mod运算符?

var images = [ 
     {img_path: "1/1.jpg"}, 
     {img_path: "1/2.jpg"}, 
     {img_path: "1/3.jpg"}, 
     {img_path: "1/4.jpg"}, 
     {img_path: "1/5.jpg"}, 
     {img_path: "1/6.jpg"}, 
     {img_path: "1/7.jpg"}, 
     {img_path: "1/8.jpg"}, 
     {img_path: "1/9.jpg"}, 
     {img_path: "1/10.jpg"} 
    ]; 

我的车把模板的代码如下所示:

<script id="gallery-template" type="text/x-handlebars-template">   
    @{{#each images}} 
      @{{#compare @index '%' 4}} 
       <div class="outer"> 
      {{/compare}} 
      <img src="@{{img_path}}" /> 
      @{{#compare @index '%' 8}} 
       </div> 
      {{/compare}} 
    @{{/each}} 
</script> 

    Handlebars.registerHelper('compare', function (lvalue, operator, rvalue, options) { 

    var operators, result; 

    if (arguments.length < 3) { 
     throw new Error("Handlerbars Helper 'compare' needs 2 parameters"); 
    }  

    if (options === undefined) { 
     options = rvalue; 
     rvalue = operator; 
     operator = "==="; 
    } 

    operators = { 
     '==': function (l, r) { return l == r; }, 
     '===': function (l, r) { return l === r; }, 
     '!=': function (l, r) { return l != r; }, 
     '!==': function (l, r) { return l !== r; }, 
     '<': function (l, r) { return l < r; }, 
     '>': function (l, r) { return l > r; }, 
     '<=': function (l, r) { return l <= r; }, 
     '>=': function (l, r) { return l >= r; }, 
     'typeof': function (l, r) { return typeof l == r; }, 
     '%': function (l, r) { return l % r == 0; } 
    }; 

    if (!operators[operator]) { 
     throw new Error("Handlerbars Helper 'compare' doesn't know the operator " + operator); 
    } 

    result = operators[operator](lvalue, rvalue); 

    if (result) { 
     return options.fn(this); 
    } else { 
     return options.inverse(this); 
    } 

}); 

但我的第一个div创建逻辑看起来不错,这,但根据这个关闭div是我无法实现的。任何帮助将非常感激。它应该准确地打破4,如果我有10,那么它应该关闭最后2个,即4,4,2。如果需要,也可以打开以更改json模式来实现此目的。

回答

0

我设法通过调整位与助手和函数调用这样做:

 <script id="gallery-template" type="text/x-handlebars-template">   
     @{{#each images}} 

      @{{#compare @index '%' 4 @last}} 
       <div class="container"> 
      @{{/compare}} 

      <img src="@{{img_path}}"> 

      @{{#compare @index '!%' 4 @last}} 
       </div> 
      @{{/compare}} 

     @{{/each}} 
    </script> 

而且通过增加额外的运营商并通过lastval的辅助函数

'!%': function (l, r) { 
    if(islast === true) 
    return true; l= l+1; 
    return l % r == 0; 
}