跳转到内容

Keystatic & Astro

Keystatic 是一个开源的无头内容管理系统,它允许你结构化你的内容并与 GitHub 同步。

使用你的包管理器的 astro add 命令,将 Markdoc(用于内容条目)和 React(用于 Keystatic 管理界面仪表盘)集成添加到你的 Astro 项目中。

终端窗口
npx astro add react markdoc

你还需要两个 Keystatic 包

终端窗口
npm install @keystatic/core @keystatic/astro

在你的 Astro 配置文件中,从 @keystatic/astro 添加 Astro 集成

astro.config.mjs
import { defineConfig } from 'astro/config'
import react from '@astrojs/react'
import markdoc from '@astrojs/markdoc'
import keystatic from '@keystatic/astro'
// https://astro.js.cn/config
export default defineConfig({
integrations: [react(), markdoc(), keystatic()],
output: 'static',
})

需要一个 Keystatic 配置文件来定义你的内容模式。这个文件也允许你将项目连接到一个特定的 GitHub 仓库(如果你决定这样做的话)。

在项目根目录下创建一个名为 keystatic.config.ts 的文件,并添加以下代码来定义你的存储类型(local)和一个内容集合(posts

keystatic.config.ts
import { config, fields, collection } from '@keystatic/core';
export default config({
storage: {
kind: 'local',
},
collections: {
posts: collection({
label: 'Posts',
slugField: 'title',
path: 'src/content/posts/*',
format: { contentField: 'content' },
schema: {
title: fields.slug({ name: { label: 'Title' } }),
content: fields.markdoc({
label: 'Content',
}),
},
}),
},
});

Keystatic 现在已经配置好,可以根据你的模式管理你的内容。

要启动你的 Keystatic 管理界面仪表盘,请启动 Astro 的开发服务器

终端窗口
npm run dev

在浏览器中访问 http://127.0.0.1:4321/keystatic 来查看正在运行的 Keystatic 管理界面。

  1. 在 Keystatic 管理界面仪表盘中,点击“Posts”集合。

  2. 使用按钮创建一篇新文章。添加标题“我的第一篇文章”和一些内容,然后保存文章。

  3. 现在,这篇新文章应该在你的“Posts”集合中可见。你可以从此仪表盘页面查看和编辑你的单篇文章。

  4. 返回查看你的 Astro 项目文件。你现在会发现在 src/content/posts 目录中有一个新的 .mdoc 文件,对应这篇新文章

    • 目录src/
      • 目录content/
        • 目录posts/
          • my-first-post.mdoc
  5. 在你的代码编辑器中导航到该文件,并验证你是否能看到你输入的 Markdown 内容。例如

    ---
    title: My First Post
    ---
    This is my very first post. I am **super** excited!

使用 Astro 的内容集合 API 来查询和显示你的文章和集合,就像你在任何 Astro 项目中所做的一样。

以下示例显示了每篇文章标题的列表,并带有指向单个文章页面的链接。

---
import { getCollection } from 'astro:content'
const posts = await getCollection('posts')
---
<ul>
{posts.map(post => (
<li>
<a href={`/posts/${post.slug}`}>{post.data.title}</a>
</li>
))}
</ul>

要显示单篇文章的内容,你可以导入并使用 <Content /> 组件来将你的内容渲染成 HTML

---
import { getEntry } from 'astro:content'
const post = await getEntry('posts', 'my-first-post')
const { Content } = await post.render()
---
<main>
<h1>{post.data.title}</h1>
<Content />
</main>

关于查询、筛选、显示你的集合内容等更多信息,请参阅完整的内容集合文档

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

你可能还想将 Keystatic 连接到 GitHub,这样你就可以在项目的已部署实例上管理内容。

更多 CMS 指南

贡献 社区 赞助