This introduction to content material collections in Astro is excepted from Unleashing the Energy of Astro, out there now on SitePoint Premium.
To utilize content material collections, Astro designates a particular folder: src/content material. Subsequently, we are able to create subfolders inside this location, every producing particular person content material collections. As an example, we may create collections resembling src/content material/dev-blog and src/content material/corporate-blog.

Every content material assortment may be configured in a config file—/src/content material/config.js (or .ts)—the place we have now the choice to make use of assortment schemas utilizing Zod.
Zod is a “TypeScript-first schema validation with static sort inference” that’s built-in into Astro. Right here’s an instance of how this might take form:
// src/content material/config.js
import { z, defineCollection } from 'astro:content material';
const devBlogCollection = defineCollection({
schema: z.object({
title: z.string(),
writer: z.string().default('The Dev Group'),
tags: z.array(z.string()),
date: z.date(),
draft: z.boolean().default(true),
description: z.string(),
}),
});
const corporateBlogCollection = defineCollection({
schema: z.object({
title: z.string(),
writer: z.string(),
date: z.date(),
featured: z.boolean(),
language: z.enum(['en', 'es']),
}),
});
export const collections = {
devblog: devBlogCollection,
corporateblog: corporateBlogCollection,
};
Within the code above, we’re defining two content material collections—one for a “developer weblog” and one for a “company weblog”. The defineCollection methodology permits us to create a schema for any given assortment. For the “developer weblog”, we’re making a schema the place the articles for this weblog class should have a title (string), writer (string defaulting to “The Dev Group”), tags (array of strings), date (date sort), draft (Boolean defaulting to true) and an outline (string).
For the “company weblog”, our schema is a little bit bit completely different: we have now a string for each the title and the writer. Date (knowledge sort) can also be going to be required by the content material, in addition to the featured (Boolean) flag and a language (enum), which might both be set to en or es.
Lastly, we’re exporting a collections object with two properties, devblog and corporateblog. These can be used afterward.
Markdown Recordsdata and Frontmatter
The examples on this tutorial about content material assortment assume that the .md recordsdata additionally embrace frontmatter matching the schema specified above within the configuration file. For instance, that is what a pattern “company weblog” put up would appear like:
---
title: 'Purchase!!'
writer: 'Jack from Advertising and marketing'
date: 2023-07-19
featured: true
language: 'en'
---
# Some Advertising and marketing Promo
That is the most effective product!
Slug Creation
Astro will mechanically generate slugs for posts based mostly on the file title. For instance, the slug for first-post.md can be first-post. Nonetheless, if we offer a slug entry in our frontmatter, Astro will respect that and use our customized slug.
Keep in mind that the properties specified within the export const collections object should match the folder names the place the content material goes to dwell. (Additionally observe that they’re case delicate!)
Querying Information
As soon as we have now all of the Markdown recordsdata in place (in our case, that will be underneath src/content material/devblog and src/content material/corporateblog) and our config.js file prepared, we are able to begin to question knowledge from the collections, which is an easy course of:
---
import { getCollection } from 'astro:content material';
const allDevPosts = await getCollection('devblog');
const allCorporatePosts = await getCollection('corporateblog');
---
<pre>{JSON.stringify(allDevPosts)}</pre>
<pre>{JSON.stringify(allCorporatePosts)}</pre>
As seen above, the getCollection methodology can be utilized to retrieve all of the entries from a given assortment (once more, referencing the exported assortment names from earlier). Within the instance above, we retrieve all of the posts from each the “developer weblog” (devblog) and from the “company weblog” (corporateblog). Within the template, we merely return the uncooked knowledge utilizing JSON.stringify().
We also needs to look at the info that’s being displayed through JSON.stringify(), and we should always take observe that, aside from the frontmatter knowledge, we additionally get an id, a slug, and a physique property returned to make use of the place the latter incorporates the put up’s content material.
We will additionally filter for drafts or posts written in a selected language within the frontmatter part by iterating by means of all articles like this:
import { getCollection } from 'astro:content material';
const spanishEntries = await getCollection('corporateblog', ({ knowledge }) => {
return knowledge.language === 'es';
});
getCollection returns all of the posts, however we are able to additionally use getEntry to return a single entry from inside a set:
import { getEntry } from 'astro:content material';
const singleEntry = await getEntry('corporateblog', 'pr-article-1');
getCollection vs getEntries
Whereas there are two methods to return a number of posts from collections, there’s a refined distinction between the 2 of them. getCollection() retrieves an inventory of content material assortment entries by assortment title, whereas getEntries() retrieves a number of assortment entries from the identical assortment.
The Astro documentation offers the instance of getEntries() getting used to retrieve content material when utilizing reference entities (for instance, an inventory of associated posts).
The idea of associated posts is the place we are able to reference an array of posts from a set. This may be achieved by including the next to the schema when utilizing the defineCollection methodology:
import { defineCollection, reference, z } from 'astro:content material';
const devblog = defineCollection({
schema: z.object({
title: z.string(),
relatedPosts: z.array(reference('weblog')),
}),
});
Within the code above, we’re additionally importing reference and utilizing that when including relatedPosts to our schema. (Notice that we are able to name this no matter we would like, resembling recommendedPosts or followupPosts.)
To make use of these relatedPosts, the suitable slug values ought to be added to the frontmatter a part of the Markdown:
title: "This can be a put up"
relatedPosts:
- A associated put up # `src/content material/devblog/a-related-post.md
Reference entities are outlined within the config.js file for the content material assortment and use the reference methodology from Zod:
const weblog = defineCollection({
sort: 'content material',
schema: z.object({
title: z.string(),
relatedPosts: z.array(reference('weblog')).optionally available(),
writer: reference('writer'),
}),
});
const writer = defineCollection({
sort: 'knowledge',
schema: z.object({
title: z.string(),
}),
});
Additionally, discover the utilization of sort: 'content material' and sort: 'knowledge'. On this case, the gathering encompasses each content material authoring codecs resembling Markdown (sort: 'content material') and knowledge codecs like JSON or YAML (sort: 'knowledge').
Displaying the Content material
Now that we all know methods to question knowledge, let’s talk about methods to truly show it in a formatted means. Astro supplies a handy methodology known as render() to render the complete content material of the Markdown right into a built-in Astro element known as <Content material />. How we construct and show the content material can also be going to be pushed by whether or not we have now static web site era or server-side rendering mode.
For pre-rendering, we are able to use the getStaticPaths() methodology:
// /src/pages/posts/[...slug].astro
---
import { getCollection } from 'astro:content material';
export async perform getStaticPaths() {
const blogEntries = await getCollection('weblog');
return blogEntries.map(entry => ({
params: { slug: entry.slug }, props: { entry },
}));
}
const { entry } = Astro.props;
const { Content material } = await entry.render();
---
<h1>{entry.knowledge.title}</h1>
<Content material />
Within the code above, we’re utilizing getStaticPaths(). (We coated this methodology within the second tutorial of this collection as a method to cater for dynamic routes.) We then depend on Astro.props to seize the entry, which goes to be an object that incorporates the metadata concerning the entry, an id, a slug, and a render() methodology. This methodology is answerable for rendering the Markdown entry to HTML within the Astro template, and it does so by making a <Content /> element. What’s wonderful about that is that every one we have to do now’s add the <Content material /> element to our template and we’ll be capable to see the Markdown content material rendered into HTML.
Need to study extra about Astro, the trendy all-in-one framework to construct quicker, content-focused web sites? Take a look at Unleashing the Energy of Astro, out there now on SitePoint Premium.


