创建一个可以在Ember-CLI中迭代一定次数的for循环 [英] Create a for loop that will iterate a certain number of times in Ember-CLI
问题描述
{{#incremented-for 2}}
块输出
{ / incremented-for}}
我尝试将其设置为组件,但无法找出一种方法使其工作。我也试图把它设置为一个帮手,并且能够找到似乎应该有效的代码:
export函数incrementedFor(n,block){
var accum ='';
for(var i = 0; i accum + = block.fn(i);
return accum;
}
导出默认值Ember.Handlebars.makeBoundHelper(incrementedFor);
但是我收到一条错误,说:
未捕获错误:断言失败:registerBoundHelper生成的帮助程序不支持使用Handlebars块。有没有人有任何想法,为什么这种方法可能不会工作,甚至更好的是,一个更好的在Ember-cli中这样做的方法?解决方案根据文档,绑定的帮助者不支持块 - 请参阅 here
您可以为组件创建一个增量,如下所示。创建一个期望次
属性的组件。然后,您可以有一个 numOfTimes
属性返回长度次
的数组。最后,您可以使用 #each
和 yield
帮助者的组合来显示您的内容。
组件代码:
从ember导入Ember;
导出默认Ember.Component.extend({
numOfTimes:Ember.computed('times',function(){
const times = parseInt(this.get '));
return new Array(times);
})
});
组件模板:
{{#each numOfTimes as | time |}}
{{yield}}
{{/ each}}
组件使用情况:
{{#increment-for times = 2}}
< div>怎么样?< / div>
{{/ increment-for}}
工作解决方案 here
I am in a situation in which I would like to be able to have a component or helper that would allow me to iterate a number of times and output the enclosed block each time. Something like this:
{{#incremented-for 2}}
block to output
{{/incremented-for}}
I tried to set this up as a component, but was not able to figure out a way to make it work. I also tried to set it up as a helper, and was able to find some code that seems like it should work:
export function incrementedFor(n, block) {
var accum = '';
for(var i = 0; i < n; ++i)
accum += block.fn(i);
return accum;
}
export default Ember.Handlebars.makeBoundHelper(incrementedFor);
but i get an error that says:
Uncaught Error: Assertion Failed: registerBoundHelper-generated helpers do not support use with Handlebars blocks.
Does anyone have any thoughts as to why this approach might not be working or, even better, a better way to do this in Ember-cli?
解决方案 According to the docs, bound helpers do not support blocks - see here
You can create a increment-for
component as follows. Create a component that expects a times
property. Then, you can have a numOfTimes
property that returns an array with length times
. Finally, you can use a combination of #each
and yield
helpers to display your content.
Component code:
import Ember from 'ember';
export default Ember.Component.extend({
numOfTimes: Ember.computed('times', function() {
const times = parseInt(this.get('times'));
return new Array(times);
})
});
Component template:
{{#each numOfTimes as |time|}}
{{ yield }}
{{/each}}
Component usage:
{{#increment-for times=2 }}
<div>How goes it?</div>
{{/increment-for}}
Working solution here
这篇关于创建一个可以在Ember-CLI中迭代一定次数的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!