Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SvelteKit: how do I do slug-based dynamic routing?

I am a newbie on Svelte and in coding in general. I'd prefer to learn SvelteKit (Svelte@Next) rather than sapper since that seems to be where Svelte is heading.

For my personal project, I need to support dynamic routing based on url slugs. How do I do that in SvelteKit? For example, if I have /blog directory and need to pull content based on its "id", how would I do that?

The part that I am having difficulty with is accessing the URL slug parameter.

Thanks in advance.

like image 948
Johny Chen Avatar asked Jan 28 '21 02:01

Johny Chen


People also ask

What is dynamic routing in programming?

Dynamic routing, also called adaptive routing, is a process where a router can forward data via a different route for a given destination based on the current conditions of the communication circuits within a system.


2 Answers

  • you can create a file with the [brackets] : touch src/routes/blog/[slug].svelte

Vscode tree

And paste the following code

<script>
    import { page } from '$app/stores';
</script>

{$page.params.slug}

Then navigate to your app http://localhost:3000/blog/123

You should see your result

result svelte kit slug

In order to create content for the http://localhost:3000/blog page, you can modify src/routes/blog/index.svelte

like image 187
KillianGDK Avatar answered Oct 21 '22 02:10

KillianGDK


Caveat - the info in my reply probably may not be valid as SvelteKit matures, but from experiments I have done thus far, this works:

Parameter based routing is similar to the sveltejs/sapper-template. You should learn how Sapper does it first. Lets say I have a route blog with a single param slug (/blog/page-1 & /blog/page-2)

  1. Create a route component in routes/blog named [slug].svelte
  2. Copy the content from the sveltejs/sapper-template example.
  3. Rename the preload function to load with a single parameter such as ctx
  4. Alter the return object to append your slug property to props
export async function load(ctx) {
  let slug = ctx.page.params.slug
  return { props: { slug }}
}

If your blog has multiple params for the slug (/blog/2021/01/29/this-is-a-slug), you can remove [slug].svelte and create a file name [...data].svelte and change your load method to:

export async function load(ctx) {
  let [year, month, day, slug] = ctx.page.params.data;
  return { props: { data: { year, month, day, slug }}}
}

Don't forget to define your data property as an object. Here's a typescript example:

<script lang="ts">
    export let data: { slug:  string, year: number, month: number, day: number };
</script>

From there use the values as {data.slug}, etc

Happy hacking

like image 3
user2526098 Avatar answered Oct 21 '22 02:10

user2526098