Implementing dynamic routing based on slug in SvelteKit primarily involves two steps: creating a dynamic route file and writing the corresponding logic to handle this route.
Step 1: Creating a Dynamic Route File
In SvelteKit, routing is handled through the file system. Specifically, you need to create a file or folder enclosed in square brackets within the src/routes directory, which represents a dynamic segment. For example, if you want to create a route based on an article's slug, you can create a file named [slug].svelte. The file path might look like this:
shellsrc └── routes └── articles └── [slug].svelte
In this example, any URL such as /articles/hello-world will be mapped to the articles/[slug].svelte file.
Step 2: Handling Dynamic Routing in the Svelte File
In the [slug].svelte file, you can use the load hook to retrieve the slug and load the corresponding data based on it. The load hook is a server-side function designed to load and pass data before the page renders.
Here is a simple example demonstrating how to use the dynamic slug within the load hook:
svelte<script context="module"> export async function load({ params }) { const { slug } = params; // Assume we have a function fetchArticle that uses the slug to fetch the article const article = await fetchArticle(slug); if (article) { return { props: { article } }; } return { status: 404, error: new Error('Article not found') }; } </script> <script> export let article; </script> <article> <h1>{article.title}</h1> <div>{article.content}</div> </article>
In this code example, we first retrieve the slug from the URL using params.slug, then use this slug to fetch the corresponding article from a backend API or database. If the article exists, we pass the article data to the component via the props property of the returned object. If the article does not exist, we return a 404 error.
Conclusion
By following these steps, you can implement dynamic routing based on slug in SvelteKit. This approach makes it straightforward and simple to dynamically load content based on URL variables, making it ideal for building blogs, news websites, or any web application requiring dynamic content.