简体   繁体   English

创建一个在Ember-CLI中迭代一定次数的for循环

[英]Create a for loop that will iterate a certain number of times in Ember-CLI

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? 有没有人想过为什么这种方法可能不起作用,或者更好的是,在Ember-cli中更好的方法呢?

As a complement to the answer of @Kalman and you would use the ember-composable-helper addon, it's even simpler. 作为@Kalman答案的补充,你会使用ember-composable-helper插件,它甚至更简单。

By using the repeat helper, a loop is easily created: 通过使用重复助手,可以轻松创建循环:

{{#each (repeat 3) as |empty|}}
  I will be rendered 3 times
{{/each}}

According to the docs, bound helpers do not support blocks - see here 根据文档,绑定帮助程序不支持块 - 请参阅此处

You can create a increment-for component as follows. 您可以按如下方式创建increment-for组件。 Create a component that expects a times property. 创建一个需要times属性的组件。 Then, you can have a numOfTimes property that returns an array with length times . 然后,您可以使用numOfTimes属性返回长度为times的数组。 Finally, you can use a combination of #each and yield helpers to display your content. 最后,您可以使用#eachyield帮助器的组合来显示您的内容。

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 工作方案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM