From 8399a4893e4132f5567766b9be98fe32adfbcceb Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Mon, 14 Jun 2021 17:21:00 -0700 Subject: [PATCH] new collections API docs (#416) * new collections API docs * docs updates * Update docs/collections.md Co-authored-by: Drew Powers <1369770+drwpow@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Drew Powers <1369770+drwpow@users.noreply.github.com> * respond to code review Co-authored-by: Drew Powers <1369770+drwpow@users.noreply.github.com> --- docs/collections.md | 272 +++++++++++++++++++++++--------------------- 1 file changed, 142 insertions(+), 130 deletions(-) diff --git a/docs/collections.md b/docs/collections.md index 3e67c2c82..244dffba5 100644 --- a/docs/collections.md +++ b/docs/collections.md @@ -1,107 +1,80 @@ # 🍱 Collections -## ❓ What are Collections? +## What are Collections? -[Fetching data is easy in Astro][docs-data]. But what if you wanted to make a paginated blog? What if you wanted an easy way to sort data, or filter data based on part of the URL? Or generate an RSS 2.0 feed? When you need something a little more powerful than simple data fetching, Astro’s Collections API may be what you need. +Astro Collections help you break up a larger set of data into multiple pages. Examples of use-cases include: -An Astro Collection is similar to the general concept of Collections in static site generators like Jekyll, Hugo, Eleventy, etc. It’s a general way to load an entire data set. But one big difference between Astro Collections and traditional static site generators is: **Astro lets you seamlessly blend remote API data and local files in a JAMstack-friendly way.** To see how, this guide will walk through a few examples. If you’d like, you can reference the [blog example project][example-blog] to see the finished code in context. +- Pagination: `/posts/1`, `/posts/2`, etc. +- Grouping content by author: `/author/fred`, `/author/matthew`, etc. +- Grouping content by some tag: `/tags/red`, `/tags/blue`, etc. +- Working with remote data +- Mixing remote and local data -## 🧑‍🎨 How to Use +**When to use Collections: When you need to reuse a single template to generate multiple pages from a larger dataset.** If you just want to generate a single page (ex: a long list of every post on your site) then you can just fetch that data on a normal Astro page without using the Collection API. -By default, any Astro component can fetch data from any API or local `*.md` files. But what if you had a blog you wanted to paginate? What if you wanted to generate dynamic URLs based on metadata (e.g. `/tag/:tag/`)? Or do both together? Astro Collections are a way to do all of that. It’s perfect for generating blog-like content, or scaffolding out dynamic URLs from your data. -Let’s pretend we have some blog posts written already. This is our starting project structure: +## Collections API -``` -└── src/ - └── pages/ - └── post/ - └── (blog content) -``` +To create a new Astro Collection, you must do three things: -The first step in adding some dynamic collections is deciding on a URL schema. For our example website, we’re aiming for the following URLs: +1. Create a new file in the `src/pages` directory that starts with the `$` symbol. This is required to enable the Collections API. + - Example: `src/pages/$posts.astro` -> `/posts/1`, `/posts/2`, etc. + - Example: `src/pages/$tags.astro` -> `/tags/:tag` (or `/tags/:tag/1`) +2. Define and export the `collection` prop: `collection.data` is how you'll access the data for every page in the collection. Astro populates this prop for you automatically. It MUST be named `collection` and it must be exported. + - Example: `export let collection;` +3. Define and export `createCollection` function: this tells Astro how to load and structure your collection data. Check out the examples below for documentation on how it should be implemented. It MUST be named `createCollection` and it must be exported. + - Example: `export async function createCollection() { /* ... */ }` + - API Reference: [createCollection][collection-api] -- `/post/:post`: A single blog post page -- `/posts/:page`: A list page of all blog posts, paginated, and sorted most recent first -- `/tag/:tag`: All blog posts, filtered by a specific tag -Because `/post/:post` references the static files we have already, that doesn’t need to be a collection. But we will need collections for `/posts/:page` and `/tag/:tag` because those will be dynamically generated. For both collections we’ll create a `/src/pages/$[collection].astro` file. This is our new structure: - -```diff - └── src/ - └── pages/ - ├── post/ - │ └── (blog content) -+ ├── $posts.astro -> /posts/1, /posts/2, … -+ └── $tag.astro -> /tag/:tag/1, /tag/:tag/2, … -``` - -💁‍ **Tip**: Any `.astro` filename beginning with a `$` is how it’s marked as a collection. - -In each `$[collection].astro` file, we’ll need 2 things: - -```js -// 1. We need to mark “collection” as a prop (this is a special reserved name) -export let collection: any; - -// 2. We need to export an async createCollection() function that will retrieve our data. -export async function createCollection() { - return { - async data() { - // return data here to load (we’ll cover how later) - }, - }; -} -``` - -These are important so your data is exposed to the page as a prop, and also Astro has everything it needs to gather your data and generate the proper routes. How it does this is more clear if we walk through a practical example. - -#### Example 1: Simple pagination - -Our blog posts all contain `title`, `tags`, and `published_at` in their frontmatter: - -```md ---- -title: My Blog Post -tags: - - javascript -published_at: 2021-03-01 09:34:00 ---- - -# My Blog post - -… -``` - -There’s nothing special or reserved about any of these names; you’re free to name everything whatever you’d like, or have as much or little frontmatter as you need. +## Example: Simple Pagination ```jsx -// /src/pages/$posts.astro --- +// Define the `collection` prop. export let collection: any; +// Define a `createCollection` function. export async function createCollection() { - const allPosts = Astro.fetchContent('./post/*.md'); // load data that already lives at `/post/:slug` - allPosts.sort((a, b) => new Date(b.published_at) - new Date(a.published_at)); // sort newest -> oldest (we got "published_at" from frontmatter!) - - // (load more data here, if needed) - + const allPosts = Astro.fetchContent('../posts/*.md'); // fetch local posts. + allPosts.sort((a, b) => a.title.localeCompare(b.title)); // sort by title. return { - async data() { - return allPosts; - }, - pageSize: 10, // how many we want to show per-page (default: 25) + // Because you are not doing anything more than simple pagination, + // its fine to just return the full set of posts for the collection data. + async data() { return allPosts; }, + // number of posts loaded per page (default: 25) + pageSize: 10, }; } - -function formatDate(date) { - return new Date(date).toUTCString(); -} --- - - Blog Posts: page {collection.page.current} + Pagination Example: Page Number {collection.page.current} + + + {collection.data.map((post) => ( +

{post.title}

+ + Read Post + ))} + + +``` + +## Example: Pagination Metadata + +```jsx +--- +// In addition to `collection.data` usage illustrated above, the `collection` +// prop also provides some important metadata for you to use, like: `collection.page`, +// `collection.url`, `collection.start`, `collection.end`, and `collection.total`. +// In this example, we'll use these values to do pagination in the template. +export let collection: any; +export async function createCollection() { /* See Previous Example */ } +--- + + + Pagination Example: Page Number {collection.page.current} @@ -112,8 +85,8 @@ function formatDate(date) { {collection.data.map((post) => (

{post.title}

- Read - )} + Read Post + ))}