跳转到内容

ButterCMS & Astro

ButterCMS 是一个无头 CMS 和博客引擎,允许你发布结构化内容并在你的项目中使用。

在本节中,我们将使用 ButterCMS SDK 将你的数据引入到 Astro 项目中。开始之前,你需要准备好以下内容

  1. 一个 Astro 项目 - 如果你还没有 Astro 项目,我们的安装指南将帮助你快速启动并运行。

  2. 一个 ButterCMS 账户。如果你还没有账户,可以注册免费试用。

  3. 你的 ButterCMS API 令牌 - 你可以在设置页面上找到你的 API 令牌。

  1. 在你的项目根目录下创建一个 .env 文件,并将你的 API 令牌添加为环境变量

    .env
    BUTTER_TOKEN=YOUR_API_TOKEN_HERE
  2. 将 ButterCMS SDK 安装为依赖项

    终端窗口
    npm install buttercms
  3. 在你的项目中新建一个 src/lib/ 目录,并在其中创建一个 buttercms.js 文件

    src/lib/buttercms.js
    import Butter from "buttercms";
    export const butterClient = Butter(import.meta.env.BUTTER_TOKEN);

这将使用你的 API 令牌对 SDK 进行身份验证,并将其导出以在你的整个项目中使用。

要获取内容,请导入此客户端并使用其 retrieve 函数之一。

在本例中,我们检索一个集合,它有三个字段:一个短文本 name、一个数字 price 和一个所见即所得(WYSIWYG) description

src/pages/ShopItem.astro
---
import { butterClient } from "../lib/buttercms";
const response = await butterClient.content.retrieve(["shopitem"]);
interface ShopItem {
name: string,
price: number,
description: string,
}
const items = response.data.data.shopitem as ShopItem[];
---
<body>
{items.map(item => <div>
<h2>{item.name} - ${item.price}</h2>
<p set:html={item.description}></p>
</div>)}
</body>

该接口反映了字段类型。所见即所得(WYSIWYG)的 description 字段加载为 HTML 字符串,set:html 允许你渲染它。

同样,你可以检索一个页面并显示其字段

src/pages/ShopItem.astro
---
import { butterClient } from "../lib/buttercms";
const response = await butterClient.page.retrieve("*", "simple-page");
const pageData = response.data.data;
interface Fields {
seo_title: string,
headline: string,
hero_image: string,
}
const fields = pageData.fields as Fields;
---
<html>
<title>{fields.seo_title}</title>
<body>
<h1>{fields.headline}</h1>
<img src={fields.hero_image} />
</body>
</html>
  • 添加你的!

更多 CMS 指南

贡献 社区 赞助