跳到主要內容

正如我們在路由介紹中所看到的,版面配置是一種在不同路由之間共享 UI 和資料載入邏輯的方式。

有時,在不影響路由的情況下使用版面配置會很有用 — 例如,您可能需要您的 /app/account 路由在驗證後才能訪問,而您的 /about 頁面則向所有人開放。我們可以使用「路由群組」來做到這一點,它是一個括號內的目錄。

透過將 account 重新命名為 (authed)/account,然後將 app 重新命名為 (authed)/app 來建立 (authed) 群組。

現在,我們可以透過建立 src/routes/(authed)/+layout.server.js 來控制對這些路由的存取權限。

src/routes/(authed)/+layout.server.js
import { redirect } from '@sveltejs/kit';

export function load({ cookies, url }) {
	if (!cookies.get('logged_in')) {
		redirect(303, `/login?redirectTo=${url.pathname}`);
	}
}

如果您嘗試訪問這些頁面,您將被重新導向到 /login 路由,該路由在 src/routes/login/+page.server.js 中有一個表單動作,用於設定 logged_in cookie。

我們也可以透過新增 src/routes/(authed)/+layout.svelte 檔案來為這兩個路由新增一些 UI

src/routes/(authed)/+layout.svelte
<script>
	let { children } = $props();
</script>

<form method="POST" action="/logout">
	<button>log out</button>
</form>

在 GitHub 上編輯此頁面

1
2
3
4
<h1>home</h1>
 
<p>this is the home page.</p>