应用的不同路由通常会共享通用 UI。我们可以使用适用于同一目录中所有路由的 +layout.svelte 组件,而不必在每个 +page.svelte 组件中重复它。
¥Different routes of your app will often share common UI. Instead of repeating it in each +page.svelte component, we can use a +layout.svelte component that applies to all routes in the same directory.
在这个应用中,我们有两条路由,src/routes/+page.svelte 和 src/routes/about/+page.svelte,它们包含相同的导航 UI。让我们创建一个新文件 src/routes/+layout.svelte...
¥In this app we have two routes, src/routes/+page.svelte and src/routes/about/+page.svelte, that contain the same navigation UI. Let’s create a new file, src/routes/+layout.svelte...
src/routes/
├ about/
│ └ +page.svelte
├ +layout.svelte
└ +page.svelte...并将重复的内容从 +page.svelte 文件移动到新的 +layout.svelte 文件中。{@render children()} 标签是页面内容将被渲染的位置:
¥...and move the duplicated content from the +page.svelte files into the new +layout.svelte file. The {@render children()} tag is where the page content will be rendered:
<script>
let { children } = $props();
</script>
<nav>
<a href="/">home</a>
<a href="/about">about</a>
</nav>
{@render children()}<script lang="ts">
let { children } = $props();
</script>
<nav>
<a href="/">home</a>
<a href="/about">about</a>
</nav>
{@render children()}+layout.svelte 文件适用于每个子路由,包括兄弟 +page.svelte(如果存在)。你可以将布局嵌套到任意深度。
¥A +layout.svelte file applies to every child route, including the sibling +page.svelte (if it exists). You can nest layouts to arbitrary depth.
<nav>
<a href="/">home</a>
<a href="/about">about</a>
</nav>
<h1>home</h1>
<p>this is the home page.</p>