0

In a spacebars template, I have a javascript array x and an index into it i, eg.

Template.test.helpers({
    'foo': function() {
        return {
            x: ['aa','bb','cc'],
            i: 1
        }
    }
});

I can access fixed elements of x in the template with {{ x.[1] }}:

{{template name="test"}}
    {{#with foo}}
        {{x.[1]}}
    {{/with}}
{{/template}}

But {{ x.[i] }} doesn't work.

How can I access x[i]? Thanks!

2 Answers 2

2

One solution is to define a custom helper:

Template.test.helpers({
    'getElement': function(a, i) {
        return a[i];
    }
});

And then in the template, use:

{{ getElement x i }}
Sign up to request clarification or add additional context in comments.

Comments

0

With such a basic example, I think your helper solution is the most straightforward; however, the goal should always be to move the logic away from the view layer (helpers & html), which is why if spacebars seems limiting, it's just a gentle reminder to refactor.

For more complex problems, a cleaner approach might be to resolve x[i] before you need to use it in your template, or turn x into an object. For example, save x[i] to a data context, or a module object & access it directly. Referencing things by their array index makes life suck when you revisit the code in a month...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.