英文:
Variable Routes in SvelteKit that Always Hit the Same File
问题
我一直在阅读SvelteKit文档的高级路由部分,但我不能完全弄清楚如何做某事。
我希望所有路由都能访问相同的 +page.server.ts
文件:
import type { PageServerLoad } from '../$types';
export const load = (async ({ params }) => {
console.log('Logging in +page.server.ts');
console.log(params);
}) satisfies PageServerLoad;
/a/b/c
应该记录:
{
first: 'a',
second: 'b',
third: 'c'
}
/a/b
应该记录:
{
first: 'a',
second: 'b',
third: ''
}
/a
应该记录:
{
first: 'a',
second: '',
third: ''
}
我认为我的文件夹结构应该如下所示:
/routes
- /first
- /first/second
- /first/second/third
但我需要它们都是可选的,并且始终访问/routes
内的+page.server.ts
。
英文:
I've been reading the advanced routing section of the SvelteKit docs, and I can't quite figure out how to do something.
I want all routes to hit the same +page.server.ts
file:
import type { PageServerLoad } from '../$types';
export const load = (async ({ params }) => {
console.log('Logging in +page.server.ts');
console.log(params);
}) satisfies PageServerLoad;
/a/b/c
should log:
{
first: 'a',
second: 'b',
third: 'c'
}
/a/b
should log:
{
first: 'a',
second: 'b',
third: ''
}
/a
should log:
{
first: 'a',
second: '',
third: ''
}
I think my folder structure should look like this:
/routes
- /first
- /first/second
- /first/second/third
But I need them all to be (optional)
and always hit the +page.server.ts
inside /routes
.
How can I accomplish this?
答案1
得分: 1
如果您希望将某些内容应用于所有路由,请将其设为布局,因此在这种情况下是 +layout.server.ts
。
可选参数使用 [[parameter]]
,因此您会得到 routes/[[first]]/[[second]]/[[third]]
。
但是,如果未设置它们,它们将不会出现在 params
中,因此如果您想要一个默认值,例如空字符串,您需要在代码中自行设置。
const resolved = {
first: '',
second: '',
third: '',
...params,
};
console.log(resolved)
英文:
If you want something to apply to all routes, make it a layout, so in this case +layout.server.ts
.
Optional parameters use [[parameter]]
, so you get routes/[[first]]/[[second]]/[[third]]
.
But they do not appear in params
if not set, so if you want a default like an empty string you have to set that yourself in code.
const resolved = {
first: '',
second: '',
third: '',
...params,
};
console.log(resolved)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论