Astro - How to Create Dynamic Pages at the Root of your website
Astro is an amazing framework for creating interactive websites by allowing developers to use their favorite framework underneath. It is an ideal solution for creating static websites, web apps and more.
If you are an astro developer, here is a quick hack in how to create dynamic pages at the root of your website, such as /about , /[page-one], /[page-two].
In the following code snippet, we will demonstrate how to achieve that.
Here, you can see that we created dynamic pages based on array selected page ID that matches the Markdown files in our content directory.
Code
---
import Site from '../site.config.json'
import { getCollection } from "astro:content";
export async function getStaticPaths() : Promise<any> {
// var pagesArr = ["about","api","goals","how-to-use","privacy-policy"]
return Site.pages.map((page)=>{
return {params: {page: page}}
})
}
const pages = await getCollection("pages");
const path: String = Astro.params["page"];
let page = pages.find((page: any) => {
if(!page || !page.data || !page.slug){
return
}
return page.slug == Astro.params["page"];
});
const { Content } = await page.render();
---
<div class="prose dark:prose-invert p-10 w-full lg:w-8/12 mx-auto">
<div class="py-4">
{Site.pages.map((page)=>(
<>
<a href={"/"+page} class="p-1x text-xs capitalizex uppercase mx-1 text-gray-500 hover:text-gray-800 ">{page}</a>
</>
)
)}
</div>
<article class="prose dark:prose-invert p-10x w-full ">
<h1 class="text-4xl">{page.data.title}</h1>
<div class="grid grid-cols-1">
<p class="text-xs">Author: {page.data.author} <br/>{page.data.date}</p>
</div>
<Content />
</article>
</div>