Getting index of outer for loop when iterating over 2 dimensional array

87 views Asked by At

I am iterating over a 2 dimensional array in a jsrender template. I would like to get indexes of both 'for' loops (inner and outer). Is it possible? I know I can get the index of the current (inner) 'for' loop using #index variable. But how can I get external index? Example

  {{for cachedImages}}
  <tr>
    {{for #data}}
    <td><img src="/Cache/{{:#outerIndex}}/{{:#index}}"/></td>
    {{/for}}
  {{/for}}
1

There are 1 answers

0
BorisMoore On BEST ANSWER

You can step up through parents, and use:

{{for cachedImages}}
  <tr>
    {{for #data}}
      <td><img src="/Cache/{{:#parent.parent.index}}/{{:#index}}"/></td>
    {{/for}}
  </tr>
{{/for}}

Alternatively you can define a contextual index variable in the outer loop that you can access from within nested contexts:

{{for cachedImages}}
  <tr>
    {{for #data ~outerIndex=#index}}
      <td><img src="/Cache/{{:~outerIndex}}/{{:#index}}"/></td>
    {{/for}}
  </tr>
{{/for}}

See also some other replies such as: JsRender Access parent index in nested template