a CheatSheet
- All routes are inside the folder
src/routes/
. - Every route is a folder:
src/routes/about
forhttps://myblog.org/about/
. - The folders name is the name of the route in the browser.
- There are no
index.*
files for routes, instead: - Every rechable route (-folder) must contains a
+page.svelte
file to represent the content. - A dynamic route uses braces
[]
for their variables -
routes/atricle-[slug]/
formyblog.org/article-1
ormyblog.org/article-last
.
-
- Inside the
routes/atricle-[slug]/+page.svelte
you can get theslug
via theload()
function.
- Inside the
- Inside the
routes/
folder you can hide folders and files with an underscore_
, to hide them for the SvelteKit-Router.
- Every route can have their own layout, contains in the
+layout.svelte
file. - Every subroute inherits the layout of its parent-route, instead it has its own
+layout.svelte
file.
- Before rendering the page (
+page.svelte
) SvelteKit will look for files inside a route-folder named like+page.js
or+page.server.js
to run theload()
function inside of them. - If you use
TypeScript
the files are named corresponding:+page.ts
or+page.server.ts
. - The
load()
function will return thedata
object as prop to the+page.svelte
file. - To execute a
load()
function for all subroutes inside a route, create a+layout.js
with theload()
function inside.
+page.js
will be executed on the server and inside the client (browser).page.server.js
will only be executed on the server, so it can respond to HTTP requests likeGET
orPOST
.
routes
│ +layout.svelte
│ +page.svelte
│
└───about
│ +page.svelte
└───article-[slug]
+page.js
+page.svelte
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<slot></slot>
<h1>Home</h1>
<h1>About</h1>
import { error } from '@sveltejs/kit';
/** @type {import('./$types').PageLoad} */
export function load({ params }) {
if (params.slug === 'hello-world') {
return {
title: 'Hello world!',
content: 'Welcome to our blog. Lorem ipsum dolor sit amet...'
};
}
throw error(404, 'Not found');
}
<script>
/** @type {import('./$types').PageData} */
export let data;
</script>
<h1>{data.title}</h1>
<div>{@html data.content}</div>