Astro cheatsheet
Astro: Routing and content
5 common Astro tasks.
Create pages from files
Files in src/pages become routes. [slug] is a dynamic segment.
src/pages/index.astro # /
src/pages/about.astro # /about
src/pages/blog/[slug].astro # /blog/anything
Generate dynamic pages at build time
getStaticPaths lists the values for a dynamic route in a static site.
---
export function getStaticPaths() {
return [
{ params: { slug: "first" }, props: { title: "First post" } },
{ params: { slug: "second" }, props: { title: "Second post" } },
];
}
const { title } = Astro.props;
---
<h1>{title}</h1>
Define a content collection
Describe a folder of Markdown files with a schema, so front matter is validated and typed.
// src/content.config.ts
import { defineCollection, z } from "astro:content";
import { glob } from "astro/loaders";
const blog = defineCollection({
loader: glob({ pattern: "**/*.md", base: "./src/content/blog" }),
schema: z.object({
title: z.string(),
date: z.coerce.date(),
draft: z.boolean().default(false),
}),
});
export const collections = { blog };
Query a collection
Fetch the entries of a collection, filtered and sorted.
---
import { getCollection } from "astro:content";
const posts = (await getCollection("blog", ({ data }) => !data.draft))
.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
---
<ul>
{posts.map((post) => <li><a href={`/blog/${post.id}`}>{post.data.title}</a></li>)}
</ul>
Render a Markdown entry
Render the Markdown body of a collection entry.
---
import { getEntry, render } from "astro:content";
const post = await getEntry("blog", "first-post");
const { Content } = await render(post);
---
<Content />