How do you create routes with optional parameters in Sapper?

断了今生、忘了曾经 提交于 2020-08-07 06:18:21

问题


Let's say I have a /foo route. But sometimes people hit /foo with a language parameter: /fr/foo. And other times they might hit it with a language and a country: /ca/fr/foo

So I need a routing table like

[country]/[language]/foo 
[language]/foo 
/foo 

That all direct to the same page.

Should I create a tree like this?

src/routes
└── [country]
    └── [language]
        └── foo.svelte

If that's the answer then how do I direct [language]/foo to [country]/[language]/foo?

I don't see any optional params in the docs


回答1:


Optional parameters aren't yet supported, but you can almost fake it with 'rest routes' (which I've just realised aren't yet documented 🤦‍♂️) — routes/[...parts]/foo.svelte would render foo.svelte with a page.params.parts array that contained the preceding segments.

Unfortunately that doesn't match /foo, which it arguably should. I've raised an issue: https://github.com/sveltejs/sapper/issues/765




回答2:


In my case I needed /dashboard/reset/TOKEN/ID route. I made it worked with the following structure:

[acool@localhost cool-sapper-project]$ tree src/routes/
src/routes/
├── dashboard
│   ├── reset
│   │   └── [...parts].svelte

The above will make TOKEN and ID parameters available in params in your page:

<script context="module">
 export async function preload({ params }, session) {
 console.log(JSON.stringify(params));
}
</script>

Output:

{"parts":["2fd4e1c67a2d28fced849ee1bb76e7391b93eb12","1"]}

Good Luck!



来源:https://stackoverflow.com/questions/56403072/how-do-you-create-routes-with-optional-parameters-in-sapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!