Union find
Union find

Reputation: 8150

How to loop through an array of objects in a Svelte template?

How do we pass an array to a Svelte template and loop over the contents?

My main.js looks like:

import App from './App.html';

const app = new App({
  target: document.body,
  data: [{name: 'hello'}, { name: 'world'}]
});

export default app;

My App.html file looks like:

{#each cats as cat}
    <h1>Hello {cat.name}!</h1>
{/each}

<style>
    h1 {
        color: purple;
    }
</style>

This seems like it should work.. but nothing appears. I've tried double curly braces as well for the each template.

Upvotes: 0

Views: 4329

Answers (1)

Rich Harris
Rich Harris

Reputation: 29605

Your data should be an object that contains an array, it can't just be an array. So for that template, this:

import App from './App.html';

const app = new App({
  target: document.body,
  data: {
    cats: [{name: 'hello'}, { name: 'world'}]
  }
});

Upvotes: 7

Related Questions