Lesson 2
Reusable Code Blocks with Snippets in Svelte
Introduction to Reusable Code Blocks

In the previous lesson, you learned how to handle asynchronous data in Svelte using the #await block. This allowed you to fetch data from an API, manage loading and error states, and update the UI dynamically based on user interaction. Now, we’ll shift our focus to another powerful feature in Svelte: reusable code blocks.

Reusable code blocks are essential for writing clean, maintainable, and efficient code. They allow you to define a piece of code once and use it multiple times throughout your application. In Svelte, this is achieved using snippets. Snippets are reusable blocks of markup that can be rendered with different data, making them ideal for components like cards, lists, or any other repetitive UI elements.

In this lesson, you’ll learn how to define and use snippets in Svelte. By the end, you’ll be able to create a reusable ProductCard snippet, filter and render it based on specific criteria, and style it dynamically. This will help you build modular and scalable components in your Svelte applications.

Creating a Snippet in Svelte

To create a snippet in Svelte, you use the {#snippet} block. A snippet is essentially a reusable template that can accept data as an argument. Once defined, you can render the snippet using the {@render} directive. Let’s start by creating a simple snippet for a product card.

Here’s an example of how to define a ProductCard snippet:

svelte
1{#snippet ProductCard(product)} 2 <div class="product-card {product.category.toLowerCase()}"> 3 <h4>{product.name}</h4> 4 <p>Category: {product.category}</p> 5 <p>Price: ${product.price}</p> 6 </div> 7{/snippet}

In this code:

  • The {#snippet ProductCard(product)} block defines a snippet named ProductCard that accepts a product object as an argument.
  • Inside the snippet, we use the product object to dynamically display the product’s name, category, and price.
  • The class attribute includes a dynamic class based on the product’s category, which we’ll use later for styling.

To render this snippet, you use the {@render} directive:

svelte
1{@render ProductCard(product)}

This renders the ProductCard snippet with the provided product data. Snippets are incredibly useful for reducing redundancy and keeping your code DRY (Don’t Repeat Yourself).

Filtering and Rendering Snippets

Now that you know how to define and render a snippet, let’s explore how to filter and render snippets dynamically based on specific criteria. In our example, we’ll render ProductCard snippets for products in two categories: "Electronics" and "Accessories."

Here’s how you can filter and render snippets:

svelte
1<h2>Electronics</h2> 2<div class="product-list"> 3 {#each products.filter(product => product.category === "Electronics") as product (product.id)} 4 {@render ProductCard(product)} 5 {/each} 6</div> 7 8<h2>Accessories</h2> 9<div class="product-list"> 10 {#each products.filter(product => product.category === "Accessories") as product (product.id)} 11 {@render ProductCard(product)} 12 {/each} 13</div>

In this code:

  • We use the #each block to iterate over the filtered list of products.
  • The .filter() method is used to include only products that match the specified category.
  • For each filtered product, we render the ProductCard snippet using {@render}.

This approach allows you to dynamically render snippets based on specific conditions, making your components more flexible and reusable.

Styling Snippets

To make your snippets visually appealing, you can add CSS classes and styles. In our example, we’ll apply dynamic styles to the ProductCard snippet based on the product’s category.

Here’s how you can style the snippet:

svelte
1<style> 2 .product-list { 3 display: flex; 4 gap: 10px; 5 margin-bottom: 20px; 6 } 7 .product-card { 8 border-radius: 8px; 9 padding: 12px; 10 color: white; 11 width: 150px; 12 text-align: center; 13 } 14 .electronics { background-color: #007BFF; } 15 .accessories { background-color: #28A745; } 16</style>

In this code:

  • The .product-list class styles the container for the product cards, using a flexbox layout with a gap between items.
  • The .product-card class styles the individual product cards, including padding, border radius, and text alignment.
  • The .electronics and .accessories classes apply category-specific background colors to the product cards.

By combining dynamic classes with CSS, you can create visually consistent and category-specific styles for your snippets.

Putting It All Together

Let’s combine everything we’ve learned into a complete example. Here’s the full code for rendering and styling ProductCard snippets based on product categories:

svelte
1<script> 2 let products = $state([ 3 { id: 1, name: "Laptop", category: "Electronics", price: 1200 }, 4 { id: 2, name: "Smartphone", category: "Electronics", price: 800 }, 5 { id: 3, name: "Headphones", category: "Accessories", price: 150 }, 6 { id: 4, name: "Keyboard", category: "Accessories", price: 100 }, 7 { id: 5, name: "Monitor", category: "Electronics", price: 300 } 8 ]); 9</script> 10 11{#snippet ProductCard(product)} 12 <div class="product-card {product.category.toLowerCase()}"> 13 <h4>{product.name}</h4> 14 <p>Category: {product.category}</p> 15 <p>Price: ${product.price}</p> 16 </div> 17{/snippet} 18 19<h2>Electronics</h2> 20<div class="product-list"> 21 {#each products.filter(product => product.category === "Electronics") as product (product.id)} 22 {@render ProductCard(product)} 23 {/each} 24</div> 25 26<h2>Accessories</h2> 27<div class="product-list"> 28 {#each products.filter(product => product.category === "Accessories") as product (product.id)} 29 {@render ProductCard(product)} 30 {/each} 31</div> 32 33<style> 34 .product-list { 35 display: flex; 36 gap: 10px; 37 margin-bottom: 20px; 38 } 39 .product-card { 40 border-radius: 8px; 41 padding: 12px; 42 color: white; 43 width: 150px; 44 text-align: center; 45 } 46 .electronics { background-color: #007BFF; } 47 .accessories { background-color: #28A745; } 48</style>

This code defines a ProductCard snippet, filters and renders it for products in the "Electronics" and "Accessories" categories, and applies dynamic styles based on the product’s category. The result is a clean, modular, and visually appealing product listing.

Summary and Practice Prep

In this lesson, you’ve learned how to create and use snippets in Svelte to build reusable code blocks. We covered how to define a snippet, pass data to it, and render it dynamically using the {@render} directive. You also learned how to filter and render snippets based on specific criteria and style them dynamically using CSS.

In the upcoming practice exercises, you’ll have the opportunity to apply these concepts by creating and using snippets in different scenarios. You’ll also experiment with filtering and styling snippets to build modular and scalable components. Remember to experiment with the code and explore further to deepen your understanding of snippets in Svelte.

Great job completing this lesson! You’re now ready to take on the challenges of building reusable components with snippets in Svelte. Keep up the good work!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.