2013-08-05 42 views
7

我創建幻燈片 - 所以有3個圖像的每一個DIV像這樣每個在灰燼指數以及模和車把

<div> 
    <img /> 
    <img /> 
    <img /> 
</div> 

</div> 
    <img /> 
    <img /> 
    <img /> 
</div> 

沒有在互聯網代碼的工作完美無缺 -

https://github.com/johanpoirier/resthub-backbone-stack/commit/8a318477d56c370d2a0af4da6eae9999c7bb29da

http://jaketrent.com/post/every-nth-item-in-handlebars-loop/

http://rockycode.com/blog/handlebars-loop-index/

http://www.arlocarreon.com/blog/javascript/handlebars-js-everyother-helper/

是的,包括堆棧溢出的答案。

任何人都可以提供一些在當前時期完美工作的代碼(Ember/Handlebar版本)嗎?

我有車型的陣列,所以我想這樣做

{{#each model}} 
    {{if index % 3 == 0}} 
    {{/if}} 
{{/each}} 
+0

你有沒有看着HTTP ://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional/9405113#9405113有相當多的例子來編寫自定義條件助手。也*索引*可通過'@ index' – colymba

回答

13

我已經發現index@index不從模板內工作,但你可以從內訪問幫手。

我在這裏做一個例子說明了這一點:

http://jsbin.com/egoyay/1/edit

編輯:添加代碼來回答,展現{{else}}

把手幫手(非灰燼使用):

Handlebars.registerHelper('ifIsNthItem', function(options) { 
    var index = options.data.index + 1, 
     nth = options.hash.nth; 

    if (index % nth === 0) 
    return options.fn(this); 
    else 
    return options.inverse(this); 
}); 

用法:

<ol> 
{{#each model}} 
    <li> 
    {{#ifIsNthItem nth=3}} 
     Index is a multiple of 3 
    {{else}} 
     Index is NOT a multiple of 3 
    {{/ifIsNthItem}} 
    </li> 
{{/each}} 
</ol> 
+0

哇你的東西完美無瑕。非常感謝! – David

+1

不錯。我發現'options.data.view.contentIndex'不可用,但通過'options.data.index'訪問索引。 – kontur

+0

這很好。你會怎麼做同樣的事情,但是有能力在混合中添加其他的東西? '{{ifIsNthItem nth = 3}}做這個{{else}}做一些其他的{{ifIsNthItem}}' – carter

2

如果您在each幫手指定itemViewClass,那麼它會爲每個項目視圖,並設置contentIndex屬性:

{{#each model itemViewClass="Ember.View"}} 
    {{view.contentIndex}} 
{{/each}} 

在灰燼V1.1.0測試

+1

沒有指定itemViewClass,我們可以使用_view.contentIndex。但是#each內的#if幫手不起作用。 – Champ