乐闻世界logo
搜索文章和话题

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

1个答案

1

When developing web applications with SvelteKit, implementing slug-based dynamic routing is a common requirement. It enables you to display different content based on URL parameters (e.g., article titles or product IDs). Below, I'll provide a detailed explanation of how to set up slug-based dynamic routing in SvelteKit.

Step 1: Creating Dynamic Route Files

In SvelteKit, routing is handled through the file system. To create a slug-based dynamic route, you need to create a file surrounded by square brackets within the src/routes directory. For example, if you want to display articles based on their slug, you can create a file named [slug].svelte.

Example:

shell
src └── routes └── blog └── [slug].svelte

In this structure, any URL like /blog/some-article-title will be matched to the blog/[slug].svelte file.

Step 2: Reading and Using the Slug Parameter

In your [slug].svelte file, you can use SvelteKit's load hook to read the slug parameter and fetch data based on it. The load hook runs on the server side, making it ideal for data fetching operations.

svelte
<script context="module"> export async function load({ params }) { const { slug } = params; const response = await fetch(`https://api.yoursite.com/articles/${slug}`); const article = await response.json(); if (response.ok) { return { props: { article } }; } else { return { status: response.status, error: new Error(`Could not load the article: ${slug}`) }; } } </script> <script> export let article; </script> <article> <h1>{article.title}</h1> <div>{article.content}</div> </article>

In the above code, the load function retrieves the slug part of the current URL via params.slug and uses it to fetch article data from an API. Then, the article data is passed to the component via props.

Step 3: Handling Load Errors

In real-world applications, handling errors is crucial. Within the load function, if an error occurs during the request, you can return an object containing the HTTP status code and error message, allowing SvelteKit to display the appropriate error page based on this information.

Summary

By doing this, you can implement slug-based dynamic routing in your SvelteKit application and display different content based on various URL slugs. This is particularly useful for scenarios like blogs and product detail pages. Hopefully this explanation will be helpful to you! If you have any further questions, I'd be happy to discuss them.

2024年8月16日 21:47 回复

你的答案