如何在车把中使用 mod 运算符?

How to use mod operator in handlebars?

我需要为以下 JSON 代码添加一个 div 包含 4 张图片:

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 架构。

我设法通过像这样调整帮助程序和函数调用来做到这一点:

     <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; 
 }