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] }}
{{ x.[1] }}
:
{{template name="test"}}
{{#with foo}}
{{x.[1]}}
{{/with}}
{{/template}}
But {{ x.[i] }}
doesn't work.
How can I access x[i]
? Thanks!
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 }}
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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.