Search code examples
ember.jsember-cli

How to iterate from a given number range?


In an ember template. Is it possible to do something similar to pseudo code:

 <ul>
  {{#each [1..100] as |item|}}
    <li>{{#link-to "articles.index" (query-params page=item)}}{{item}}{{/link-to}}</li>
  {{/each}}
 </ul>

Which would create something similar to:

 <ul>
  <li><a href="localhost/articles?page=1">1</a></li>
  <li><a href="localhost/articles?page=2">2</a></li>
  <li><a href="localhost/articles?page=3">3</a></li>
  // so forth
 </ul>

Solution

  • Not really, but it's easy to implement with sub-expressions in HTMLBars. So if you create a helper like so:

    App.RangeHelper = Ember.Helper.helper(function(params) {
      var range = [];
      for(var i=params[0]; i < params[1]; ++i){
        range.push(i);
      }
      return range;
    });
    

    You can do:

    {{#each (range 1 100) as |item|}}
      <li>{{#link-to "articles.index" (query-params page=item)}}{{item}}{{/link-to}}</li>
    {{/each}}
    

    I'm mimicking the python range function, so keep in mind it ends at 99 in my example.