tildeio / htmlbars

A variant of Handlebars that emits DOM and allows you to write helpers that manipulate live DOM nodes
MIT License
1.6k stars 193 forks source link

Access array by index inside "each" block #388

Open dmoreno opened 9 years ago

dmoreno commented 9 years ago

I have two arrays:

var array1 = [ "a", "b", "c"];
var array2 = [ "x", "y", "z"];

And I try to interate with an each block by this way:

{{#each array1 as |item index|}}
  1. {{index}} : {{item}}
  2. {{array2.[0]}}
  3. {{array2.[index]}}
{{/each}}

First and second lines works as expected. But third line is empty.

I tried several ways but no one works:

array2.index
array2.[index]
array2.[(index)]
array2.[@index]

What is the way to interate over a second array using index? Could it be a bug?

stefanpenner commented 9 years ago

ah looks like you are trying to zip two arrays together?

an interesting idea may be.

{{#each (zip array1 array2) as |tuple, index|}}
  {{tuple.0}} || {{tuple.1}}
{{/each}}

we could go all lisp (but it feels strange)

{{#each (zip array1 array2) as |tuple, index|}}
  {{car tuple}} || {{cdr tuple}}
{{/each}}
stefanpenner commented 9 years ago

{{array2.[index]}}

some people may view this as WAT, but I think it would be good.

dmoreno commented 9 years ago

I think that syntax {{array2.[index]}} makes sense and it is consistent with the rest of the htmlbars syntax.

And your idea about zip helper is interesting too. But, at least for me, it could be the second option.

stefanpenner commented 9 years ago

cc @mmun

krisselden commented 9 years ago

So, you can do it with native arrays and the get() helper or create an index-of helper. But maybe this warrants a syntax? We should either close and open a different issue with that suggestion or change the title of this issue.

http://emberjs.jsbin.com/wocedobavu/1/edit?html,js,console,output

mmun commented 9 years ago

array2.[index] already means something. It's would be breaking to change it. We could consider array2[index].

egemon commented 7 years ago

Any updates on that?

mmun commented 7 years ago

@egemon This should have been closed as working. What's the issue you're running into? You should be able to use (get array index) in Ember to fetch an array index.

mmun commented 7 years ago

Possibly related https://github.com/emberjs/ember.js/pull/15366

egemon commented 7 years ago

From what version this should work?