+layout.svelte in SvelteKit: What It Is and How It Works
+layout.svelte in SvelteKit is a special file that defines a shared layout for multiple pages. It wraps page content with common UI elements like headers or footers, so you don’t repeat code on every page.How It Works
Think of +layout.svelte as a frame around your pictures. Instead of adding the same frame to every picture separately, you create one frame and put all pictures inside it. In SvelteKit, this file wraps all pages in its folder and subfolders, providing a consistent look and feel.
When you navigate between pages, the layout stays the same, and only the page content changes inside it. This makes your app faster and easier to maintain because shared parts like navigation bars or footers live in one place.
Example
This example shows a +layout.svelte that adds a header and footer around page content.
<script> // You can add layout-specific logic here </script> <header> <h1>My Website</h1> <nav> <a href="/">Home</a> <a href="/about">About</a> </nav> </header> <main> <slot /> </main> <footer> <p>© 2024 My Website</p> </footer>
When to Use
Use +layout.svelte when you want to share common UI parts across multiple pages, like headers, footers, sidebars, or consistent styling. It is perfect for apps where many pages share the same structure.
For example, an online store can use a layout to keep the shopping cart icon and main menu visible on every page. Or a blog can use it to keep the site title and footer consistent.
Key Points
- +layout.svelte wraps pages in its folder and subfolders.
- It helps avoid repeating UI code on every page.
- Use the
<slot />tag to insert page content inside the layout. - Layouts can be nested by placing
+layout.sveltefiles in subfolders. - Layouts improve app speed by keeping shared UI persistent during navigation.
Key Takeaways
+layout.svelte defines shared UI that wraps multiple pages in SvelteKit.<slot /> element to display page-specific content inside the layout.+layout.svelte files in subfolders for different sections.