1

私が次のようなものを持っている場合:

{
 people: [
          "Yehuda Katz",
          "Alan Johnson",
          "Charles Jolley"
         ]
}

ハンドルバーの各値の位置を取得するにはどうすればよいですか?

{{#each people}}
   {{this}}
   <!--{{this.position}} -->

{{/each}}

答えは

           Yehuda Katz
           0
           Alan Johnson
           1
           Charles Jolley
           2
4

2 に答える 2

1

これを実現するために、「each_with_index」などの独自のブロック式を定義できます。このカスタム式を作成する方法については、次のハンドルバーのドキュメントで確認できます: http://handlebarsjs.com/#block-expressions

これを行うための迅速で汚れた方法を次に示します。

var people = [ 'Yehuda Katz', 'Alan Johnson', 'Charles Jolley' ];

var source = '{{#each_with_index people}}' +
             '{{ this.index }}: {{ this.item }}\n' +
             '{{/each_with_index}}';

Handlebars.registerHelper('each_with_index', function(items, options) {
  var output = '';
  var item_count = items.length;
  var item;

  for (var index = 0; index < item_count; index ++) {
    item = items[index];

      output = output + options.fn({ item: item, index: index });
  }

  return output;
});

var $output = $('#output');
var template = Handlebars.compile(source);
var result = template({ people: people });

$output.html(result);

動作を確認するには: http://jsfiddle.net/EECFR/1/

于 2012-12-20T20:08:23.990 に答える
0

使用@index:

{{#each people}}
  {{this}}
  {{@index}}
{{/each}}

JSFiddle デモ(Carl のものを変更)

http://handlebarsjs.com/#iterationから:

それぞれのアイテムをループするとき、必要に応じて現在のループ インデックスを参照できます。{{@index}}

{{#each array}}
  {{@index}}: {{this}}
{{/each}}
于 2014-02-20T17:56:40.990 に答える