Skip to content

有效负载 CMS 和 Astro

PayloadCMS 是一个无头开源内容管理系统,可用于为你的 Astro 项目提供内容。

¥PayloadCMS is a headless open-source content management system that can be used to provide content for your Astro project.

¥Integrating with Astro

¥Prerequisites

  1. Astro 项目 - 如果你还没有 Astro 项目,我们的 安装指南 将立即帮助你启动并运行。
  2. MongoDB 数据库 - PayloadCMS 会在创建新项目时要求你提供 MongoDB 连接字符串。你可以在本地设置一个数据库,也可以使用 MongoDBAtlas 免费在网络上托管数据库。
  3. PayloadCMS REST API - 在设置期间创建一个 PayloadCMS 项目并将其连接到你的 MongoDB 数据库。

为你的 PayloadCMS 集合配置 Astro

标题部分 为你的 PayloadCMS 集合配置 Astro

¥Configuring Astro for your PayloadCMS collection

你的 Payload 项目模板将包含 src/collections/ 中名为 Posts.ts 的文件。如果你在安装过程中没有选择为你创建内容集合的模板,则可以通过手动添加此配置文件来创建新的 Payload CMS 集合。下面的示例显示了名为 posts 的集合的此文件,该集合需要 titlecontentslug 字段:

¥Your Payload project template will contain a file called Posts.ts in src/collections/. If you did not choose a template during installation that created a content collection for you, you can create a new Payload CMS Collection by adding this configuration file manually. The example below shows this file for a collection called posts that requires title, content, and slug fields:

src/collections/Posts.ts
import { CollectionConfig } from "payload/types";
const Posts: CollectionConfig = {
slug: "posts",
admin: {
useAsTitle: "title",
},
access: {
read: () => true,
},
fields: [
{
name: "title",
type: "text",
required: true,
},
{
name: "content",
type: "text",
required: true,
},
{
name: "slug",
type: "text",
required: true,
},
],
};
export default Posts;
  1. Import and add both Users (available in all PayloadCMS projects) and any other collections (e.g. Posts) to the available collections in the payload.config.ts file.

    src/payload.config.ts
    import { buildConfig } from "payload/config";
    import path from "path";
    import Users from "./collections/Users";
    import Posts from "./collections/Posts";
    export default buildConfig({
    serverURL: "http://localhost:4321",
    admin: {
    user: Users.slug,
    },
    collections: [Users, Posts],
    typescript: {
    outputFile: path.resolve(__dirname, "payload-types.ts"),
    },
    graphQL: {
    schemaOutputFile: path.resolve(__dirname, "generated-schema.graphql"),
    },
    });

    This will make a new collection called “Posts” appear in your PayloadCMS Dashboard next to the “Users” collection.

  2. Enter the “Posts” collection and create a new post. After saving it, you will notice the API URL appear in the bottom right corner.

  3. With the dev server running, open http://localhost:4321/api/posts in your browser. You should see a JSON file containing the post you have created as an object.

    {
    "docs":[
    {
    "id":"64098b16483b0f06a7e20ed4",
    "title":"Astro & PayloadCMS Title 🚀",
    "content":"Astro & PayloadCMS Content",
    "slug":"astro-payloadcms-slug",
    "createdAt":"2023-03-09T07:30:30.837Z",
    "updatedAt":"2023-03-09T07:30:30.837Z"
    }
    ],
    "totalDocs":1,
    "limit":10,
    "totalPages":1,
    "page":1,
    "pagingCounter":1,
    "hasPrevPage":false,
    "hasNextPage":false,
    "prevPage":null,
    "nextPage":null
    }

¥Fetching Data

通过你网站的唯一 REST API URL 和内容路径获取你的 PayloadCMS 数据。(默认情况下,PayloadCMS 将通过 /api 挂载所有路由。)然后,你可以使用 Astro 的 set:html="" 指令渲染数据属性。

¥Fetch your PayloadCMS data through your site’s unique REST API URL and the route for your content. (By default, PayloadCMS will mount all routes through /api.) Then, you can render your data properties using Astro’s set:html="" directive.

PayloadCMS 将与你的帖子一起返回一些顶层元数据。实际文档嵌套在 docs 数组中。

¥Together with your post, PayloadCMS will return some top-level metadata. The actual documents are nested within the docs array.

例如,要显示帖子标题及其内容的列表:

¥For example, to display a list of post titles and their content:

src/pages/index.astro
---
import HomeLayout from "../layouts/HomeLayout.astro";
const res = await fetch("http://localhost:5000/api/posts") // http://localhost:4321/api/posts by default
const posts = await res.json()
---
<HomeLayout title='Astro Blog'>
{
posts.docs.map((post) => (
<h2 set:html={post.title} />
<p set:html={post.content} />
))
}
</HomeLayout>

使用 PayloadCMS 和 Astro 构建博客

标题部分 使用 PayloadCMS 和 Astro 构建博客

¥Building a blog with PayloadCMS and Astro

创建一个博客索引页 src/pages/index.astro 来列出你的每篇文章,并附有指向其自己页面的链接。

¥Create a blog index page src/pages/index.astro to list each of your posts with a link to its own page.

通过 API 获取会返回一个对象数组(帖子),其中包括以下属性:

¥Fetching via the API returns an array of objects (posts) that include, among others, the following properties:

  • title

  • content

  • slug

src/pages/index.astro
---
import HomeLayout from "../layouts/HomeLayout.astro";
const res = await fetch("http://localhost:5000/api/posts") // http://localhost:4321/api/posts by default
const posts = await res.json()
---
<HomeLayout title='Astro Blog'>
<h1>Astro + PayloadCMS 🚀</h1>
<h2>Blog posts list:</h2>
<ul>
{
posts.docs.map((post) =>(
<li>
<a href={`posts/${post.slug}`} set:html={post.title} />
</li>
))
}
</ul>
</HomeLayout>

使用 PayloadCMS API 生成页面

标题部分 使用 PayloadCMS API 生成页面

¥Using the PayloadCMS API to generate pages

为每个帖子创建一个页面 src/pages/posts/[slug].astro动态生成页面

¥Create a page src/pages/posts/[slug].astro to dynamically generate a page for each post.

src/pages/posts/[slug].astro
---
import PostLayout from "../../layouts/PostLayout.astro"
const {title, content} = Astro.props
// The getStaticPaths() is required for static Astro sites.
// If using SSR, you will not need this function.
export async function getStaticPaths() {
let data = await fetch("http://localhost:5000/api/posts")
let posts = await data.json()
return posts.docs.map((post) => {
return {
params: {slug: post.slug},
props: {title: post.title, content: post.content},
};
});
}
---
<PostLayout title={title}>
<article>
<h1 set:html={title} />
<p set:html={content} />
</article>
</PostLayout>

¥Publishing your site

要部署你的网站,请访问我们的 部署指南 并按照你首选托管提供商的说明进行操作。

¥To deploy your site visit our deployment guide and follow the instructions for your preferred hosting provider.

¥Community Resources

更多 CMS 指南

Astro 中文网 - 粤ICP备13048890号