'Can I make custom nested slugs in SvelteKit?
Lets say I have a page to show information about some fictive persons, which loads dynamic data from some database.
One typical way to do this in SvelteKit is by creating a folder and file in the /routes directory, like this: /person/[id].svelte
However, I would like to have informative nested slugs based on different parameters, e.g. /country/city/street/name
Then I have an array of "persons" in js that I can match these slugs against, get the correct id and the correct svelte component to render the person in, eg. person.svelte.
[Edit]
In the same project, I might have other categories and different depths of nesting, which might look like: carcompany/navigation/navigation/car/model
[/Edit]
Is this possible?
Solution 1:[1]
I am not sure if this is one of the best practices, but as long as the documentation suggests, and I've done something similar in my projects, yes you definitely can. If you create
/[country]/[city]/[street]/[name].svelte
You can retrieve the params in the URL object of Sveltekit.
For exeample,
/south_korea/seoul/yeoksamdong/james will return
...
params : { country: 'south_korea', city: 'seoul', street: 'yeoksamdong', name: 'james'}
...
This is accessible in the load function, or from the 'page' store
export async function load(event) {
event.url.params // returns params.
return { props : {} }
}
or
import { page } from '$app/pages'
$page.url.params // returns params. notice '$'
The main difference of these are if they can be accessible from client side, or server side. However, you can refer from both sides if you return a prop from the load function.
<script context="module">
export async function load(event) {
return { props : {
params: event.url.params
} }
}
</script>
<script>
export let params;
</script>
{params.name} -> james
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
