Dav*_*vid 7 each loops handlebars.js ember.js
我正在创建一张幻灯片 - 所以每个div都有3张图像
<div>
<img />
<img />
<img />
</div>
</div>
<img />
<img />
<img />
</div>
Run Code Online (Sandbox Code Playgroud)
互联网上的代码都没有完美无瑕 -
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}}
Run Code Online (Sandbox Code Playgroud)
小智 16
我一直在模板中找到index或@index不工作,但您可以从帮助程序中访问它.
我在这里做了一个例子来证明这一点:
http://jsbin.com/egoyay/1/edit
编辑:添加代码以回答,演示{{else}}阻止
把手帮手(非Ember使用):
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);
});
Run Code Online (Sandbox Code Playgroud)
用法:
<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>
Run Code Online (Sandbox Code Playgroud)