Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emberjs increment in the template

I feel like I may be doing to much for a simple problem.

If index = 0, how do I increment index in a template.

Ideally, I would like to do something like this.

{{index+1}}

From what I understand the solution is to write a helper function like the following.

import Ember from 'ember';

export function plusOne(params) {
  return parseInt(params) + 1;
}

export default Ember.HTMLBars.makeBoundHelper(plusOne);

And then in the template you would do the following.

{{plus-one index}}

So hopefully, I am wrong and there is a much easier way to do this. And possibly a easier way to do 'simple' processing in the template. Not sure if there may be an objection because there may be 'to much' logic in the template.

Any guidance on this would be greatly appreciated.

Thanks!

like image 960
user2517182 Avatar asked Apr 16 '15 19:04

user2517182


1 Answers

The short answer is, no. There is no way to do any real computing logic in the templates. The helper is your best bet for adding 1 to index, within a template.

Of course, one would wonder why you would want to add +1 to any index anyway? possibly to label your itterations in a non-zero based way? in that case would you not render an ordered list instead?

<ol>
  {{#each model as |foo|}}
    <li>{{foo.bar}}</li>
  {{/each}}
</ol>

Resulting in:

  1. I'm a foo
  2. I'm a foo too!
  3. I'm a foo three!

another possibility is this (as an alternative to using a helper for every index)

model: ['Foo', 'Man', 'Chu']

foosWithCount: Ember.computed.map('model', function(foo, index) {
  return Ember.Object.create({
    name: foo,
    count: index + 1
  });
});

then

{{#each foosWithCount as |foo|}}
  <p>I'm {{foo.name}} and I'm #{{foo.count}}</p>
{{/each}}

Resulting in:

I'm Foo and I'm #1

I'm Man and I'm #2

I'm Chu and I'm #3

like image 140
Grapho Avatar answered Oct 06 '22 20:10

Grapho