要匹配未知數量的路徑段,請使用 [...rest]
參數,其名稱與 JavaScript 中的 rest 參數 類似。
將 src/routes/[path]
重新命名為 src/routes/[...path]
。現在路由會匹配任何路徑。
其他更具體的路由將首先進行測試,這使得 rest 參數可用作「萬用」路由。例如,如果您需要為
/categories/...
內的頁面建立自訂 404 頁面,您可以新增這些檔案src/routes/ ├ categories/ │ ├ animal/ │ ├ mineral/ │ ├ vegetable/ │ ├ [...catchall]/ │ │ ├ +error.svelte │ │ └ +page.server.js
在
+page.server.js
檔案中,在load
內使用error(404)
。
Rest 參數不需要放在最後 — 像 /items/[...path]/edit
或 /items/[...path].json
這樣的路由完全有效。
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/stores';
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>