在 routing 的第一章中,我们学习了如何使用 动态参数 创建路由。
¥In the first chapter on routing, we learned how to create routes with dynamic parameters.
有时将参数设为可选会很有帮助。一个典型的例子是,当你使用路径名来确定语言环境(/fr/...、/de/... 等等)时,但你还希望有一个默认语言环境。
¥Sometimes it’s helpful to make a parameter optional. A classic example is when you use the pathname to determine the locale — /fr/..., /de/... and so on — but you also want to have a default locale.
为此,我们使用双括号。将 [lang] 目录重命名为 [[lang]]。
¥To do that, we use double brackets. Rename the [lang] directory to [[lang]].
该应用现在无法构建,因为 src/routes/+page.svelte 和 src/routes/[[lang]]/+page.svelte 都与 / 匹配。删除 src/routes/+page.svelte。(你可能需要重新加载应用才能从错误页面恢复)。
¥The app now fails to build, because src/routes/+page.svelte and src/routes/[[lang]]/+page.svelte would both match /. Delete src/routes/+page.svelte. (You may need to reload the app to recover from the error page).
最后,编辑 src/routes/[[lang]]/+page.server.js 以指定默认语言环境:
¥Lastly, edit src/routes/[[lang]]/+page.server.js to specify the default locale:
const greetings = {
en: 'hello!',
de: 'hallo!',
fr: 'bonjour!'
};
export function load({ params }) {
return {
greeting: greetings[params.lang ?? 'en']
};
}<h1>hello!</h1>