Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a named loop variable in ractive.js?

Tags:

ractivejs

In Python, iteration gives me a named variable:

for cage in cages:
    for animal in cage.animals:
        print("The current cage is",cage)
        print("the current animal is",animal)

In Ractive templates, I don't appear to be able to do this.

{{#cages}}
    {{#animals}}
         The current animal is {{.}} or {{this}},
         but I don't know how to refer to the current cage,
         i.e. the outer loop variable

         I would like to be able to say {{cage}} has an {{animal}}
    {{/animals}}
{{/cages}}

Is there a syntax I'm not aware of?

like image 992
trvrm Avatar asked Jan 07 '23 22:01

trvrm


1 Answers

I've wondered about whether we should add an {{#each cage in cages}} or {{#each cages as cage}} syntax to handle cases like these. In lieu of that, mknecht's answer is totally valid, and something I often use myself; an alternative is to create an index reference like so:

{{#each cages :c}}
  {{#each animals}}
    The current animal is {{this}}, the current cage
    is {{cages[c]}}
  {{/each}}
{{/each}}

The difference with this method is that two-way binding will still work (though it doesn't sound like that's an issue in this case.)

like image 121
Rich Harris Avatar answered May 25 '23 03:05

Rich Harris