Skip to content

DatoCMS 和 Astro

DatoCMS 是一个基于网络的无头 CMS,用于管理你的网站和应用的数字内容。

¥DatoCMS is a web-based, headless CMS to manage digital content for your sites and apps.

¥Integrating with Astro

在本指南中,你将从 Astro 项目中的 DatoCMS 获取内容数据,然后将其显示在页面上。

¥In this guide, you will fetch content data from DatoCMS in your Astro project, then display it on a page.

¥Prerequisites

首先,你需要具备以下条件:

¥To get started, you will need to have the following:

  • Astro 项目 - 如果你还没有 Astro 项目,你可以按照我们的 安装指南 中的说明进行操作。

  • DatoCMS 账户和项目 - 如果你没有账户,你可以 注册一个免费账户

  • DatoCMS 项目的只读 API 密钥 - 你可以在项目的管理仪表板的 “设置” > “API 令牌” 下找到它。

¥Setting up the credentials

在 Astro 项目的根目录中创建一个名为 .env 的新文件(如果尚不存在)。使用 DatoCMS 管理仪表板中找到的 API 密钥添加新的环境变量,如下所示:

¥Create a new file (if one does not already exist) named .env in the root of your Astro project. Add a new environment variable as follows, using the API key found in your DatoCMS admin dashboard:

.env
DATOCMS_API_KEY=YOUR_API_KEY

对于 TypeScript 支持,请在 src/ 文件夹中的 env.d.ts 文件中声明此环境变量的类型。如果该文件不存在,你可以创建它并添加以下内容:

¥For TypeScript support, declare the typing of this environment variable in the env.d.ts file in the src/ folder. If this file does not exist, you can create it and add the following:

src/env.d.ts
interface ImportMetaEnv {
readonly DATOCMS_API_KEY: string;
}

你的根目录现在应该包含以下文件:

¥Your root directory should now include these files:

  • Directorysrc/
    • env.d.ts
  • .env
  • astro.config.mjs
  • package.json

¥Create a Model in DatoCMS

在项目的 DatoCMS 管理仪表板中,导航到 “设置” > “模块” 并创建一个名为 “家” 的新模型,并选择 “单实例” 切换开关。这将为你的项目创建一个主页。在此模型中,为页面标题添加一个新文本字段。

¥In the DatoCMS admin dashboard of your project, navigate to “Settings” > “Models” and create a new Model called “Home” with the “Single Instance” toggle selected. This will create a home page for your project. In this model, add a new text field for the page title.

导航到项目中的 “内容” 选项卡,然后单击新创建的主页。你现在可以添加标题。保存页面并继续。

¥Navigate to the “Content” tab in your project and click on your newly-created home page. You can now add a title. Save the page, and continue.

¥Fetching data

在你的 Astro 项目中,导航到将获取并显示你的 CMS 内容的页面。添加以下查询以使用 DatoCMS GraphQL API 获取 home 的内容。

¥In your Astro project, navigate to the page that will fetch and display your CMS content. Add the following query to fetch the content for home using the DatoCMS GraphQL API.

此示例显示 src/pages/index.astro 上 DatoCMS 的页面标题:

¥This example displays the page title from DatoCMS on src/pages/index.astro:

src/pages/index.astro
---
const response = await fetch('https://graphql.datocms.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${import.meta.env.DATOCMS_API_KEY}`,
},
body: JSON.stringify({
query: `query Homepage {
home {
title
}
}
`,
}),
});
const json = await response.json();
const data = json.data.home;
---
<h1>{data.title}</h1>

此 GraphQL 查询将从你的 DatoCMS 项目中获取 home 页面中的 title 字段。当你刷新浏览器时,你应该会在页面上看到标题。

¥This GraphQL query will fetch the title field in the home page from your DatoCMS Project. When you refresh your browser, you should see the title on your page.

添加动态模块化内容块

Section titled 添加动态模块化内容块

¥Adding Dynamic modular content blocks

如果你的 DatosCMS 项目包含 模块化内容,那么你需要为项目中模块化字段允许的每个内容块(例如文本部分、视频、引文块等)构建相应的 .astro 组件。

¥If your DatosCMS project includes modular content, then you will need to build a corresponding .astro component for each block of content (e.g. a text section, a video, a quotation block, etc.) that the modular field allows in your project.

下面的示例是 <Text /> Astro 组件,用于显示 DatoCMS 中的 “多段落文本” 块。

¥The example below is a <Text /> Astro component for displaying a “Multiple-paragraph text” block from DatoCMS.

src/components/Text.astro
---
export interface TextProps {
text: string
}
export interface Props {
item: TextProps
}
const { item } = Astro.props;
---
<div set:html={item.text} />

要获取这些块,请编辑 GraphQL 查询以包含你在 DatoCMS 中创建的模块化内容块。

¥To fetch these blocks, edit your GraphQL query to include the modular content block you created in DatoCMS.

在此示例中,模块化内容块在 DatoCMS 中名为 content。此查询还包括每个项目的唯一 _modelApiKey,以根据内容作者在 DatoCMS 编辑器中选择的块来检查哪个块应显示在模块化字段中。在 Astro 模板中使用 switch 语句可以根据从查询接收到的数据进行动态渲染。

¥In this example, the modular content block is named content in DatoCMS. This query also includes the unique _modelApiKey of each item to check which block should be displayed in the modular field, based on which block was chosen by the content author in the DatoCMS editor. Use a switch statement in the Astro template to allow for dynamic rendering based on the data received from the query.

以下示例表示 DatoCMS 模块化内容块,允许作者在主页上渲染的文本字段 (<Text />) 和图片 (<Image />) 之间进行选择:

¥The following example represents a DatoCMS modular content block that allows an author to choose between a text field (<Text />) and an image (<Image />) rendered on the home page:

src/pages/index.astro
---
import Image from '../components/Image.astro';
import Text from '../components/Text.astro';
const response = await fetch('https://graphql.datocms.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${import.meta.env.DATOCMS_API_KEY}`,
},
body: JSON.stringify({
query: `query Homepage {
home {
title
content {
... on ImageRecord {
_modelApiKey
image{
url
}
}
... on TextRecord {
_modelApiKey
text(markdown: true)
}
}
}
}
`,
}),
});
const json = await response.json();
const data = json.data.home;
---
<h1>{data.title}</h1>
{
data.content.map((item: any) => {
switch (item._modelApiKey) {
case 'image':
return <Image item={item} />;
case 'text':
return <Text item={item} />;
default:
return null;
}
})
}

¥Publishing your site

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

¥To deploy your website, visit our deployment guides and follow the instructions for your preferred hosting provider.

在 DatoCMS 上发布内容更改

Section titled 在 DatoCMS 上发布内容更改

¥Publish on DatoCMS content changes

如果你的项目使用 Astro 的默认静态模式,你将需要设置一个 Webhook 以在内容更改时触发新的构建。如果你使用 Netlify 或 Vercel 作为托管提供商,则当你更改 DatoCMS 中的内容时,可以使用其 Webhook 功能触发新构建。

¥If your project is using Astro’s default static mode, you will need to set up a webhook to trigger a new build when your content changes. If you are using Netlify or Vercel as your hosting provider, you can use its webhook feature to trigger a new build when you change content in DatoCMS.

要在 Netlify 中设置 Webhook:

¥To set up a webhook in Netlify:

  1. Go to your site dashboard and click on Build & deploy.

  2. Under the Continuous Deployment tab, find the Build hooks section and click on Add build hook.

  3. Provide a name for your webhook and select the branch you want to trigger the build on. Click on Save and copy the generated URL.

要在 Vercel 中设置 Webhook:

¥To set up a webhook in Vercel:

  1. Go to your project dashboard and click on Settings.

  2. Under the Git tab, find the Deploy Hooks section.

  3. Provide a name for your webhook and the branch you want to trigger the build on. Click Add and copy the generated URL.

¥Adding a webhook to DatoCMS

在你的 DatoCMS 项目管理仪表板中,导航到“设置”选项卡并单击“Webhooks”。单击加号图标创建新的 Webhook 并为其命名。在 URL 字段中,粘贴你的首选托管服务生成的 URL。作为触发器,选择适合你需求的选项。(例如:每次发布新记录时都会构建。)

¥In your DatoCMS project admin dashboard, navigate to the Settings tab and click Webhooks. Click the plus icon to create a new webhook and give it a name. In the URL field, paste the URL generated by your preferred hosting service. As Trigger, select whichever option suits your needs. (For example: build every time a new record is published.)

¥Starter project

你还可以查看 DatoCMS 市场上的 Astro 博客模板,了解如何使用 Astro 和 DatoCMS 创建博客。

¥You can also check out the Astro blog template on the DatoCMS marketplace to learn how to create a blog with Astro and DatoCMS.

More CMS guides

Astro 中文网 - 粤ICP备13048890号