0
0
Svelteframework~5 mins

Layout files (+layout.svelte)

Choose your learning style9 modes available
Introduction

Layout files help you keep parts of your website that stay the same on many pages, like headers or footers, in one place. This saves time and keeps your site organized.

You want the same header and footer on every page of your website.
You want to add a navigation menu that appears on multiple pages.
You want to apply a consistent style or structure across several pages.
You want to avoid repeating the same code in every page component.
Syntax
Svelte
<script>
  // Optional script for layout logic
</script>

<header>
  <!-- Common header content -->
</header>

<slot />

<footer>
  <!-- Common footer content -->
</footer>

The <slot /> tag is where the content of child pages will appear inside the layout.

Layout files are named +layout.svelte and placed in folders to apply to all pages inside that folder.

Examples
A simple layout with a header and footer that wraps all pages in the folder.
Svelte
<!-- +layout.svelte -->
<header>
  <h1>My Website</h1>
</header>

<slot />

<footer>
  <p>Ā© 2024 My Website</p>
</footer>
Layout with a navigation bar that shows a welcome message before page content.
Svelte
<!-- +layout.svelte -->
<script>
  let user = 'Guest';
</script>

<nav>
  <p>Welcome, {user}!</p>
</nav>

<slot />
Sample Program

This layout file adds a blue header with navigation links, a main area where page content appears, and a light footer. All pages inside src/routes will use this layout automatically.

Svelte
<!-- src/routes/+layout.svelte -->
<header style="background-color: #4a90e2; color: white; padding: 1rem;">
  <h1>My Cool Site</h1>
  <nav>
    <a href="/" style="color: white; margin-right: 1rem;">Home</a>
    <a href="/about" style="color: white;">About</a>
  </nav>
</header>

<main style="padding: 1rem;">
  <slot />
</main>

<footer style="background-color: #eee; padding: 1rem; text-align: center;">
  <small>Ā© 2024 My Cool Site</small>
</footer>
OutputSuccess
Important Notes

Layouts can be nested by placing +layout.svelte files in subfolders for different sections.

Use <slot /> to mark where child page content should appear inside the layout.

Styling inside layouts helps keep your site consistent and easier to update.

Summary

Layout files keep shared parts of your site in one place.

Use +layout.svelte with a <slot /> to wrap pages.

Layouts save time and make your site easier to manage.