2012-12-18 39 views
1

得到一個集合中的每個元素的位置。如果我有這樣的:如何使用車把

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

如何讓每一個在車把值的位置?

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

{{/each}} 

我希望答案是

  Yehuda Katz 
      0 
      Alan Johnson 
      1 
      Charles Jolley 
      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/

0

使用@index

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

JSFiddle demo

01(從卡爾的修改)

http://handlebarsjs.com/#iteration

當通過在每一循環的項目,則可以任選地通過{{@index}}

{{#each array}} 
    {{@index}}: {{this}} 
{{/each}} 
引用當前循環索引