0
0
Svelteframework~5 mins

Text interpolation with {} in Svelte

Choose your learning style9 modes available
Introduction

Text interpolation lets you show dynamic values inside your HTML easily. It helps your webpage update automatically when data changes.

Showing a user's name on a welcome message.
Displaying the current date or time that updates.
Showing the result of a calculation or variable.
Updating text based on user input instantly.
Displaying data fetched from an API.
Syntax
Svelte
<p>{variable}</p>
Use curly braces {} inside your HTML to insert JavaScript expressions or variables.
Svelte updates the displayed text automatically when the variable changes.
Examples
Shows the value of the variable name inside a paragraph.
Svelte
<p>Hello, {name}!</p>
Calculates and shows the sum of a and b directly in the text.
Svelte
<p>The sum is {a + b}</p>
Displays the current value of count, which can change over time.
Svelte
<p>{count} clicks</p>
Sample Program

This Svelte component shows a greeting with a name and a button. Each time you click the button, the count variable increases, and the displayed text updates automatically.

Svelte
<script>
  let name = 'Alice';
  let count = 0;
  function increment() {
    count += 1;
  }
</script>

<main>
  <h1>Hello, {name}!</h1>
  <button on:click={increment}>Click me</button>
  <p>You clicked {count} times.</p>
</main>
OutputSuccess
Important Notes

Text interpolation with {} works inside HTML elements and in attribute values like class or id.

You can put any JavaScript expression inside the curly braces, but keep it simple for readability.

Summary

Use {} to insert variables or expressions inside your HTML.

Svelte updates the displayed text automatically when data changes.

It makes your UI dynamic and interactive with very little code.