Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 791
John Avatar asked Mar 04 '15 20:03

John


2 Answers

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

like image 138
Kalman Avatar answered Nov 13 '22 08:11

Kalman


As a complement to the answer of @Kalman and you would use the ember-composable-helper addon, it's even simpler.

By using the repeat helper, a loop is easily created:

{{#each (repeat 3) as |empty|}}
  I will be rendered 3 times
{{/each}}
like image 9
Jacob van Lingen Avatar answered Nov 13 '22 10:11

Jacob van Lingen