2. Routing and Layouts
SvelteKit's file-system based routing is very intuitive. You define routes by creating files inside the src/routes/ directory.
2.1. Pages (+page.svelte)
Each route is defined by a +page.svelte file. This file renders the UI for that specific route.
// src/routes/about/+page.svelte
<h1>About Us</h1>
<p>This is the about page.</p>
This file corresponds to the /about path.
2.2. Layouts (+layout.svelte)
A +layout.svelte file defines UI that is shared across multiple pages. You can create a root layout that applies to all pages.
// src/routes/+layout.svelte (Global layout)
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<slot /> <!-- Page content will be injected here -->
<footer>
<p>© 2023 My App</p>
</footer>
The <slot /> element indicates where the content of the current route's +page.svelte will be inserted. Nested layouts are also possible.
2.3. Error Pages (+error.svelte)
You can define an error page using +error.svelte to display when unexpected errors occur.
// src/routes/+error.svelte
<script>
import { page } from '$app/stores';
</script>
<h1>{$page.status}: {$page.error?.message}</h1>
<p>Something went wrong.</p>