Return array item by index/variable in a meteor spacebars template
Asked Answered
L

2

0

How can I access the X item of an array inside a meteor template?

Thanks to Return array item by index in a meteor spacebars template I know how to do that for a specific index:

<p>{{array.[0]}}</p>

But my question is how to do that for a runtime defined index. Let say that X is defined and with a valid value. Why is this not working for me?

<p>{{array.[X]}}</p>
Loner answered 23/1, 2017 at 20:29 Comment(0)
S
2

You can try

<p>{{array.[index]}}</p> eg. <p>{{array.[0]}}</p>

or

{{#each getArray}}
    <div class="item" data-value="{{someHelper @index}}">
        {{this}}
    </div>
{{/each}}
Stalemate answered 23/1, 2017 at 20:36 Comment(3)
First option did not work for me. Second one works, but I'll prefer to avoid using a helper. Any other idea?Loner
@rafahoro> I don't understand your problem with a helper? security, performance, re-usability, ...?Negro
@JeanRAKOTO just to make code easy to follow (for me at least). The need to go to a helper, just to access an array, seems a bit odd.Loner
C
0

Same problem here,

I end using a general helpers, {{arrayIndex array index}}

As simple as

import { Template } from 'meteor/templating'

Template.registerHelper('arrayIndex', function (array, index) {
  return array[index]
})
Coparcener answered 28/3, 2019 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.