# Content collections

> Schema helpers the theme adds over Astro content collections.

The theme adds schema helpers on top of Astro's content collections for common
page shapes.

## Defining a collection

### The fast path: `definePageCollection`

For a standard page shape (`title`, optional `description`, optional
`heroImage`, `published`), `definePageCollection` ships the schema. `heroImage`
accepts a relative image path (validated and optimised through Astro's image
pipeline) or an absolute `http(s)://` URL for a remote, pre-encoded hero:

```ts
// src/content.config.ts
import { definePageCollection } from "astro-theme-university/schemas";

// Strict schema: unknown frontmatter fields will fail the content sync.
const pages = definePageCollection();

export const collections = { pages };
```

Pass `passthrough: true` to accept arbitrary extra frontmatter fields without
updating the schema. This is the default in the base starter example.

To extend the base schema, import `pageSchema` and use it inside a regular
`defineCollection` call, so TypeScript still infers the extended shape:

```ts
import { defineCollection } from "astro:content";
import { glob } from "astro/loaders";
import { z } from "astro/zod";
import { pageSchema } from "astro-theme-university/schemas";

const docs = defineCollection({
  loader: glob({ pattern: "**/*.{md,mdx}", base: "src/content/docs" }),
  schema: (ctx) =>
    pageSchema(ctx).extend({
      section: z.enum(["getting-started", "guides", "reference"]),
      order: z.number().default(0),
    }),
});
```

### The manual path: `defineCollection`

If your collection doesn't fit the page shape, define it the usual way with
Astro's own helpers:

```ts
import { defineCollection, z } from "astro:content";
import { glob } from "astro/loaders";

const posts = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "src/content/posts" }),
  schema: z.object({
    title: z.string(),
    description: z.string().optional(),
    date: z.coerce.date(),
    author: z.string().optional(),
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
  }),
});

export const collections = { posts };
```

Content files then go in `src/content/posts/`:

```
src/content/posts/
  first-post.md
  second-post.md
  announcing-something.md
```

Frontmatter must match the schema; TypeScript flags mismatches at build time.

## Creating a dynamic route

To render each post, create a dynamic route. For `/posts/[slug]`, that's
`src/pages/posts/[...slug].astro`:

```astro
---
import { getCollection, render } from "astro:content";
import BaseLayout from "astro-theme-university/layouts/BaseLayout.astro";
import { siteConfig } from "../../site-config";

export async function getStaticPaths() {
  const posts = await getCollection("posts", ({ data }) => !data.draft);
  return posts.map((post) => ({
    params: { slug: post.id },
    props: { post },
  }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---

<BaseLayout
  {...siteConfig}
  title={post.data.title}
  description={post.data.description}
>
  <article>
    <h1>{post.data.title}</h1>
    <time datetime={post.data.date.toISOString()}>
      {post.data.date.toLocaleDateString("en-AU", {
        year: "numeric",
        month: "long",
        day: "numeric",
      })}
    </time>
    <Content />
  </article>
</BaseLayout>
```

The [starter example](https://anucybernetics.github.io/astro-theme-university/docs/getting-started/examples/) applies the same pattern
to its `definePageCollection` collection in `src/pages/[...slug].astro`,
rendering through `ContentLayout` so the entry's `heroImage` is picked up.

## Listing posts

Query the collection and render the results:

```astro
---
import { getCollection } from "astro:content";
import BaseLayout from "astro-theme-university/layouts/BaseLayout.astro";
import { siteConfig } from "../site-config";

const posts = await getCollection("posts", ({ data }) => !data.draft);
const sorted = posts.sort(
  (a, b) => b.data.date.valueOf() - a.data.date.valueOf(),
);
---

<BaseLayout {...siteConfig} title="Posts">
  <h1>Posts</h1>
  <ul>
    {sorted.map((post) => <li>
      <a href={`/posts/${post.id}`}>{post.data.title}</a>
      <time datetime={post.data.date.toISOString()}>
        {post.data.date.toLocaleDateString("en-AU")}
      </time>
    </li>)}
  </ul>
</BaseLayout>
```

## Filtering and querying

Filter with the callback to exclude drafts, match a tag, or limit to recent
posts:

```ts
// Published posts only
const published = await getCollection("posts", ({ data }) => !data.draft);

// Posts with a specific tag
const tagged = await getCollection("posts", ({ data }) =>
  data.tags.includes("research"),
);
```

## Using MDX

Update the glob pattern to include `.mdx`:

```ts
loader: glob({ pattern: "**/*.{md,mdx}", base: "src/content/posts" }),
```
