关于 javascript:Custom handlebars each helper with index

Custom handlebars each helper with index

我编写了一个循环遍历数组的助手,但现在我一直在为每次迭代获取可用的索引。我希望在我看来打印当前项目的索引。

1
2
3
4
5
6
7
8
9
10
11
helpers: {
    each_min: function(ary, min, options) {
      if(!ary || ary.length == 0)
          return options.inverse(this);

      var result = [];
      for(var i = 0; i < min; ++i)
          result.push(options.fn(ary[i]));
      return result.join('');
    }
}

我的模板

1
2
3
4
5
6
7
{{#each_min p.name 4}}
{{#if this}}
{{index}} {{this}}
{{else}}
<p>-</p>
{{/if}}
{{/each_min}}

查看车把文档,我在 Block helpers 部分找到了相关信息。

Block helpers can also inject private variables into their child templates. This can be useful to add extra information that is not in the original context data. ... Make sure you create a new data frame in each helper that assigns its own data. Otherwise, downstream helpers might unexpectedly mutate upstream variables.

基于此,我进行了以下更改:

模板:

1
2
3
4
5
6
7
{{#each_min p.name 4}}
    {{#if this}}
        {{@index}} {{this}}
    {{else}}
        <p><center>[wp_ad_camp_2]</center></p><p>-</p>
    {{/if}}
{{/each_min}}

助手:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function(ary, min, options) {
    if(!ary || ary.length === 0) {
        return options.inverse(this);
    }
    var data;
    if (options.data) {
        data = Handlebars.createFrame(options.data);
    }

    var result = [];
    for(var i = 0; i < min; ++i) {
        if (data) {
            data.index = i;
        }
        result.push(options.fn(ary[i], {data: data}));
    }

    return result.join('');
}