正如我们在 路由介绍 中看到的,布局是一种在不同路由之间共享 UI 和数据加载逻辑的方式。
¥As we saw in the routing introduction, layouts are a way to share UI and data loading logic between different routes.
有时使用布局而不影响路由很有用 - 例如,你可能需要 /app 和 /account 路由进行身份验证,而 /about 页面向全世界开放。我们可以使用路由组(括号中的目录)来做到这一点。
¥Sometimes it’s useful to use layouts without affecting the route — for example, you might need your /app and /account routes to be behind authentication, while your /about page is open to the world. We can do this with a route group, which is a directory in parentheses.
通过将 account 重命名为 (authed)/account,然后将 app 重命名为 (authed)/app,创建一个 (authed) 组。
¥Create an (authed) group by renaming account to (authed)/account then renaming app to (authed)/app.
现在我们可以通过创建 src/routes/(authed)/+layout.server.js 来控制对这些路由的访问:
¥Now we can control access to these routes by creating 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 的表单操作。
¥If you try to visit these pages, you’ll be redirected to the /login route, which has a form action in src/routes/login/+page.server.js that sets the logged_in cookie.
我们还可以通过添加 src/routes/(authed)/+layout.svelte 文件向这两个路由添加一些 UI:
¥We can also add some UI to these two routes by adding a src/routes/(authed)/+layout.svelte file:
<script>
let { children } = $props();
</script>
{@render children()}
<form method="POST" action="/logout">
<button>log out</button>
</form><script lang="ts">
let { children } = $props();
</script>
{@render children()}
<form method="POST" action="/logout">
<button>log out</button>
</form><h1>home</h1>
<p>this is the home page.</p>