0
0
Svelteframework~5 mins

Using data in pages in Svelte

Choose your learning style9 modes available
Introduction

Using data in pages lets you show information that can change or come from outside. It makes your page useful and interactive.

Showing a list of items like products or articles on a page.
Displaying user information after they log in.
Updating the page when a user types in a form.
Showing the current date and time that changes.
Loading data from a server to show on the page.
Syntax
Svelte
<script>
  let message = 'Hello, world!';
</script>

<p>{message}</p>
Use {} curly braces to insert data into HTML.
Declare variables inside the <script> tag to use them in the page.
Examples
Shows a greeting with a name stored in a variable.
Svelte
<script>
  let name = 'Alice';
</script>

<h1>Welcome, {name}!</h1>
Displays a number inside the page text.
Svelte
<script>
  let count = 5;
</script>

<p>You have {count} new messages.</p>
Shows a list of items using a loop.
Svelte
<script>
  let items = ['Apple', 'Banana', 'Cherry'];
</script>

<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>
Sample Program

This page shows user information by using data stored in an object.

Svelte
<script>
  let user = {
    name: 'Sam',
    age: 30
  };
</script>

<main>
  <h2>User Info</h2>
  <p>Name: {user.name}</p>
  <p>Age: {user.age}</p>
</main>
OutputSuccess
Important Notes

Data inside <script> is reactive. Changing variables updates the page automatically.

Use {#each} blocks to loop over arrays and show lists.

Keep data simple and clear for easy updates and maintenance.

Summary

Use variables inside <script> to hold data.

Insert data into HTML with curly braces {}.

Use loops like {#each} to show lists dynamically.