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?
- Cleaner code - Calculate once, use multiple times
- Easier to read - Give complex calculations a name
- 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! đ
