The Astro blog sample is a great starting point but what if you want summary pages for each month or year. The sample just has an index page with all posts and that wont scale. Fortunately Astro has a solution.
The function getStaticPaths()
is a way to turn one Astro page into many. Firstly your page needs to have a variable in the name. As an example posts[year].astro
is such a file name. Next it needs to implement getStaticPaths()
and that must be the first thing your page does. The function needs to return an array that includes your variable name from the post title. Here’s an example
// This makes a list of all the years we need
export async function getStaticPaths() {
// grab all the posts
let allPosts = await Astro.fetchContent('./posts/**/*.mdx');
// get all the years
let allYears = allPosts.map( (p) => {
const [date,month,year] = p.publishDate.split(" ")
return year } );
// unique ones
let uniqueYears = [...new Set(allYears)];
// make a list of them and return them.
return uniqueYears.map( (y) => { return { params: { 'year': y }}} )
}
Now the page will be called for each item in the array. You can get the ‘instance’ with the params.
// now get and show the selected year
const {year} = Astro.request.params;
Once you have that you can process and create the page as needed. I’ve made a github sample that shows how it’s done