Kev
Kev

Reputation: 16321

Each blocks for arbitrary nested arrays

https://svelte.technology/guide#each-blocks gives an example of each blocks to output a table-like structure:

<div class='grid'>
  {{#each rows as row, y}}
    <div class='row'>
      {{#each columns as column, x}}
        <code class='cell'>
          {{x + 1}},{{y + 1}}:
          <strong>{{row[column]}}</strong>
        </code>
      {{/each}}
    </div>
  {{/each}}
</div>

The example requires this particular structure:

{
  "columns": [
    "foo",
    "bar",
    "baz"
  ],
  "rows": [
    {
      "foo": "a",
      "bar": "b",
      "baz": "c"
    },
    {
      "foo": "d",
      "bar": "e",
      "baz": "f"
    },
    {
      "foo": "g",
      "bar": "h",
      "baz": "i"
    }
  ]
}

Is there a way to use this feature if the columns are not known beforehand, or even more generally, if each row might have a different length? E.g. (for the latter):

{
  "rows": [
    [1],
    [2, 3, 4],
    [5, 6]
  ]
}

I don't see anywhere indicating a syntax for #each that can "reach into" a component's data before iterating, as it were.

Am I missing something or is the inner loop of this impossible with #each? If it is impossible, what are some other ways to do it? (E.g. can you use a function to iterate over the inner arrays and nest a secondary template?)

Upvotes: 2

Views: 1117

Answers (1)

gyre
gyre

Reputation: 16777

I'm just learning off of the documentation here, but from what I can tell you should be able to treat row as a list of cells:

<div class='grid'>
  {{#each rows as row, y}}
    <div class='row'>
      {{#each row as cell, x}}
        <code class='cell'>
          {{x + 1}},{{y + 1}}:
          <strong>{{cell}}</strong>
        </code>
      {{/each}}
    </div>
  {{/each}}
</div>

Upvotes: 2

Related Questions