0

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.

1 Answer 1

7

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'}]
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.