4

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?

Nabin
  • 11,216
  • 8
  • 63
  • 98
trvrm
  • 784
  • 5
  • 17

2 Answers2

5

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.)

Rich Harris
  • 28,091
  • 3
  • 84
  • 99
  • I would very much like to see `{{#each cage in cages}}` or `{{#each cages as cage}}`, that would make writing nested loops much easier. – trvrm Jul 22 '15 at 14:44
4

There is no explicit syntax, afaik, but you may (mis)use aliases for that: You create a new context, which renames . to cage, for example. It would look like so:

{{#cages}} {{# {cage: .} }}
  {{ cage.name }}
{{/}}{{/cages}}

A complete version is on JSFiddle

Misuse because in Ractive, you usually work on the properties of the current context object without naming the context object itself. This works fine in the nested case, too. Therefore, there is no syntax for this.

Where aliases do make sense: name-shadowing. If you need to access a cage-property with the same name as an animal-property in the inner loop, then aliases come into play. Both is demonstrated in another fiddle

mknecht
  • 1,205
  • 11
  • 20