Template Basics

Back

Loading concept...

Svelte Template Basics: Making Your Page Come Alive! 🎭

Imagine you have a magic whiteboard. You write on it, and whatever you write appears exactly as you want. But here’s the cool part—you can also make it smart! You can tell it: “Show this only if it’s sunny” or “Put my name here automatically.”

That’s what Svelte templates do. They’re like smart whiteboards for websites!


The Big Picture

graph TD A["Your Data"] --> B["Template Magic"] B --> C["What Users See"] B --> D{Decisions} D --> E["Show This"] D --> F["Show That"]

Think of it like a recipe card:

  • Your data = the ingredients
  • Your template = the recipe instructions
  • The output = the delicious dish people see

1. Template Expressions: Putting Things in Curly Braces

What is it?

A template expression is like a window into your data. You use curly braces { } to peek through and show what’s inside your variables.

Simple Example

<script>
  let name = "Alex";
  let age = 10;
</script>

<p>Hello, {name}!</p>
<p>You are {age} years old.</p>

What appears: “Hello, Alex! You are 10 years old.”

Real Life

Think of {name} like a name tag holder. Whatever name you put in the holder, that’s what shows up!

You Can Do Math Too!

<script>
  let apples = 5;
  let oranges = 3;
</script>

<p>Total fruits: {apples + oranges}</p>

Result: “Total fruits: 8”


2. Text Interpolation: Mixing Text with Data

What is it?

Text interpolation means blending your text with your data. It’s like Mad Libs—you have blanks, and Svelte fills them in!

Simple Example

<script>
  let pet = "dog";
  let petName = "Buddy";
</script>

<p>I have a {pet} named {petName}!</p>

What appears: “I have a dog named Buddy!”

Why It’s Cool

You write the sentence once. Change petName to “Max”? The page updates automatically! No rewriting needed.


3. HTML Rendering: When You Need Real HTML

The Problem

What if you want to show bold text or a link that comes from your data?

<script>
  let message = "<strong>Important!</strong>";
</script>

<!-- This shows the actual text: <strong>Important!</strong> -->
<p>{message}</p>

Oops! That shows the code, not bold text!

The Solution: @html

<script>
  let message = "<strong>Important!</strong>";
</script>

<!-- This shows: Important! (in bold) -->
<p>{@html message}</p>

Warning! Be Careful!

Only use @html with data you trust. It’s like opening your front door—only do it for friends, not strangers!

<script>
  // SAFE: You wrote this
  let safeHTML = "<em>Hello!</em>";

  // DANGEROUS: User typed this
  let userInput = "..."; // Could be bad code!
</script>

<p>{@html safeHTML}</p>

4. If Blocks: Making Decisions

What is it?

Sometimes you want to show something only when a condition is true. Like a light switch—on or off!

Simple Example

<script>
  let isLoggedIn = true;
</script>

{#if isLoggedIn}
  <p>Welcome back, friend!</p>
{/if}

When isLoggedIn is true: Shows “Welcome back, friend!” When isLoggedIn is false: Shows nothing!

The Structure

graph TD A["Check Condition"] --> B{Is it true?} B -->|Yes| C["Show the content"] B -->|No| D["Skip it"]

Real Life Example

<script>
  let hasCookie = true;
</script>

{#if hasCookie}
  <p>Yay! You have a cookie! đŸȘ</p>
{/if}

5. Else Blocks: The Other Option

What is it?

What if you want to show something different when the condition is false? That’s what :else is for!

Simple Example

<script>
  let isSunny = false;
</script>

{#if isSunny}
  <p>Wear sunglasses! 😎</p>
{:else}
  <p>Maybe bring an umbrella! ☔</p>
{/if}

When isSunny is true: “Wear sunglasses!” When isSunny is false: “Maybe bring an umbrella!”

The Flow

graph TD A["Check: Is it sunny?"] --> B{True or False?} B -->|True| C["Sunglasses message"] B -->|False| D["Umbrella message"]

6. Else If Blocks: Multiple Choices

What is it?

Sometimes you have more than two options. Like a traffic light—it’s not just on or off. It’s red, yellow, or green!

Simple Example

<script>
  let score = 85;
</script>

{#if score >= 90}
  <p>Grade: A ⭐</p>
{:else if score >= 80}
  <p>Grade: B 👍</p>
{:else if score >= 70}
  <p>Grade: C 👌</p>
{:else}
  <p>Keep trying! đŸ’Ș</p>
{/if}

With score = 85: Shows “Grade: B”

The Decision Tree

graph TD A[What's the score?] --> B{>= 90?} B -->|Yes| C["Grade A"] B -->|No| D{>= 80?} D -->|Yes| E["Grade B"] D -->|No| F{>= 70?} F -->|Yes| G["Grade C"] F -->|No| H["Keep trying"]

Another Example

<script>
  let weather = "rainy";
</script>

{#if weather === "sunny"}
  <p>Go to the beach! đŸ–ïž</p>
{:else if weather === "rainy"}
  <p>Stay inside and read! 📚</p>
{:else if weather === "snowy"}
  <p>Build a snowman! ⛄</p>
{:else}
  <p>Check the forecast!</p>
{/if}

7. Const Declaration: Creating Helpers Inside Templates

What is it?

Sometimes you need to calculate something right inside your template. The @const tag lets you create a helper value on the spot!

Simple Example

<script>
  let items = [
    { name: "Apple", price: 1 },
    { name: "Banana", price: 0.5 }
  ];
</script>

{#each items as item}
  {@const total = item.price * 1.1}
  <p>{item.name}: ${total.toFixed(2)}</p>
{/each}

This calculates price + 10% tax right there!

Why Use @const?

  1. Cleaner code - Calculate once, use multiple times
  2. Easier to read - Give complex calculations a name
  3. Works inside loops - Each item gets its own value

Another Example

<script>
  let users = [
    { first: "John", last: "Doe" },
    { first: "Jane", last: "Smith" }
  ];
</script>

{#each users as user}
  {@const fullName = `${user.first} ${user.last}`}
  <p>Welcome, {fullName}!</p>
{/each}

Quick Summary: The Template Toolbox

Tool What It Does Example
{expression} Shows data {name}
Text interpolation Mixes text + data Hello, {name}!
{@html} Renders real HTML {@html boldText}
{#if} Shows if true {#if happy}Yay!{/if}
{:else} Shows if false {:else}Aww{/if}
{:else if} Multiple conditions {:else if ok}Meh{/if}
{@const} Helper values {@const x = a + b}

The Golden Rule

Templates are just smart HTML. You already know HTML. Now you’re adding superpowers:

  • Curly braces to show data
  • Hash tags (#if) to make decisions
  • At signs (@html, @const) for special tricks

You’re not learning something totally new. You’re just making HTML smarter!


What’s Next?

Now that you understand template basics, you can:

  • Show different messages to different users
  • Create dynamic lists
  • Build interactive forms
  • Make your pages respond to user actions

You’ve got the foundation. Now go build something amazing! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.