#dynamic route [slug].astro

4 messages · Page 1 of 1 (latest)

fiery beacon
#

Hello everyone, I need help:
I'm coding astro whose job is to view post details. In the post list screen, I have an a tag to redirect with the slug extension (For example: /post/8). So in the file [slug].astro I have to declare getStaticPaths() but how can I predict the params, because the other slug is arbitrary and not fixed. How do I not have to define it first? Thanks and please help me

cursive thistleBOT
#

Hi @fiery beacon. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, you can use dynamic routes to handle arbitrary paths like the ones you're dealing with. You can define dynamic routes by including [param] or [...path] brackets in your file names to match arbitrary strings or paths. In your case, you would use [slug].astro to match any slug.

In Server-Side Rendering (SSR) mode, the routes are not built ahead of time, so the page will be served to any matching route. Since these are not “static” routes, getStaticPaths should not be used. Instead, you can use Astro.params to access the dynamic parts of the URL. Here's an example:

---const { slug } = Astro.params;---
<h1>Post: {slug}</h1>

In this example, the page will be served for any value of slug: post/1, post/2, etc.

However, if you're using Astro's default static mode, you'll use getStaticPaths() function. This function will be called at build time to generate the list of paths that become pages. You can fetch your data inside a getStaticPaths() function and map each item to an object with a params and props property. The params property will be used to generate the URL of the page and the props property will be passed to the page component as props. Here's an example:

---import { contentfulClient } from "../../lib/contentful";
import type { BlogPost } from "../../lib/contentful";

export async function getStaticPaths() {
  const entries = await contentfulClient.getEntries<BlogPost>({
    content_type: "blogPost",
  });

  const pages = entries.items.map((item) => ({
    params: { slug: item.fields.slug },
    props: {
      title: item.fields.title,
      content: documentToHtmlString(item.fields.content),
      date: new Date(item.fields.date).toLocaleDateString(),
    },
  }));
  return pages;
}---
#

In this example, the params object passes the slug property to the page, which must match the name of the dynamic route. Since our filename is [slug].astro, we use slug.

For more information, you can refer to the Astro documentation on dynamic routes (https://docs.astro.build/en/guides/routing/#dynamic-routes) and the getStaticPaths() function (https://docs.astro.build/en/reference/api-reference/#getstaticpaths).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: