Astro Content Collections
Organizing Blog Posts
The biggest change from blogging in a CMS like Wordpress and moving to Astro, is that you have to keep all of your own blog posts organized.
I like to add the date in YYYYMMDD-
to the beginning of every file, that corresponds to pubDate
, as it keeps everything in the folder in a chronologic order (although the oldest will be on top) especially as you add more posts. (which you definitely will do, right?).
Include slug: "post-slug"
to every frontmatter
- update the
YYYYMMDD
when you updatepubdate
- keep the url pretty
The Slug
The frontmatter variable: slug
does not need to be added to z
in defineCollection()
.
Slug examples
slug: "hyphens-freaking-everywhere"
or
slug: "you/can/use/a/frontslash"
I believe you need to make sure that the astro file is [...slug].astro
. I don’t know if it works with [slug].astro. It doesn’t work with [slug].astro
.
Excluding Files from Astro Build
You can filter out draft content in Astro using draft: true
.
// Example: Filter out content entries with `draft: true` only when building for production
import { getCollection } from 'astro:content';
const blogEntries = await getCollection('blog', ({ data }) => {
return import.meta.env.PROD ? data.draft !== true : true;
});
The Easier Way IMO
By adding a _
to the beginning of the filename (ex: _20240103-my-blog-post.mdx
) Astro will ignore these files in the build. It’s also a good way to visually see in VS Code which posts I’m still working on.
This also works on pages src/pages/page/_page.astro
and folders src/pages/_page/index.astro
.