创建一个将在 Ember-CLI 中迭代一定次数的 for 循环 [英] Create a for loop that will iterate a certain number of times in Ember-CLI

查看:19
本文介绍了创建一个将在 Ember-CLI 中迭代一定次数的 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够拥有一个组件或帮助程序,让我可以迭代多次并每次都输出封闭的块.像这样:

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.

有没有人想过为什么这种方法可能行不通,或者甚至更好,在 Ember-cli 中有更好的方法来做到这一点?

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

您可以创建一个 increment-for 组件,如下所示.创建一个需要 times 属性的组件.然后,您可以使用 numOfTimes 属性返回一个长度为 times 的数组.最后,您可以结合使用 #eachyield 助手来显示您的内容.

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.

组件代码:

import Ember from 'ember';

export default Ember.Component.extend({
  numOfTimes: Ember.computed('times', function() {
    const times = parseInt(this.get('times'));
    return new Array(times);
  })
});

组件模板:

{{#each numOfTimes as |time|}}
  {{ yield }}
{{/each}}

组件使用:

{{#increment-for times=2 }}
  <div>How goes it?</div>
{{/increment-for}}

工作解决方案这里

这篇关于创建一个将在 Ember-CLI 中迭代一定次数的 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆