Basic Svelte
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
未知の数のパスセグメントにマッチさせるには、[...rest] パラメータを使用します。これは、 JavaScript の残余引数(rest parameters) に似ているため、この名前が付けられました。
src/routes/[path] を src/routes/[...path] にリネームしましょう。このルート(route)はどんなパスにもマッチします。
他の、より詳細・明確(specific)なルート(routes)が最初にテストされるため、rest パラメータは ‘catch-all’ ルート(routes)として便利です。例えば、
/categories/...の中のページ用にカスタムの 404 ページを必要とする場合は、以下のファイルを追加することができます。src/routes/ ├ categories/ │ ├ animal/ │ ├ mineral/ │ ├ vegetable/ │ ├ [...catchall]/ │ │ ├ +error.svelte │ │ └ +page.server.js
+page.server.jsファイルにて、loadの内側でerror(404)のようにエラーをスローします。
Rest parameters はパスの末尾にしなければならないわけではありません。 — /items/[...path]/edit や /items/[...path].json のようなルート(route)は完全に有効です。
previous next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<script>
import { page } from '$app/state';let words = ['how', 'deep', 'does', 'the', 'rabbit', 'hole', 'go'];
let depth = $derived(page.params.path.split('/').filter(Boolean).length); let next = $derived(depth === words.length ? '/' : `/${words.slice(0, depth + 1).join('/')}`);</script>
<div class="flex">
{#each words.slice(0, depth) as word} <p>{word}</p> {/each} <p><a href={next}>{words[depth] ?? '?'}</a></p></div>
<style>
.flex {display: flex;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
}
p {margin: 0.5rem 0;
line-height: 1;
}
a {display: flex;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
font-size: 4rem;
}
</style>