ButterCMS 和 Astro
ButterCMS 是一个无头 CMS 和博客引擎,可让你发布结构化内容以用于你的项目。
¥ButterCMS is a headless CMS and blog engine that allows you to publish structured content to use in your project.
与 Astro 集成
标题部分 与 Astro 集成¥Integrating with Astro
在本节中,我们将使用 黄油 CMS SDK 将你的数据引入 Astro 项目。首先,你需要具备以下条件:
¥In this section, we’ll use the ButterCMS SDK to bring your data into your Astro project. To get started, you will need to have the following:
先决条件
标题部分 先决条件¥Prerequisites
-
Astro 项目 - 如果你还没有 Astro 项目,我们的 安装指南 将立即帮助你启动并运行。
-
ButterCMS 账户。如果你没有账户,可以 报名 免费试用。
-
你的 ButterCMS API 令牌 - 你可以在 设置 页面上找到你的 API 令牌。
设置
标题部分 设置¥Setup
-
Create a
.env
file in the root of your project and add your API token as an environment variable:.env BUTTER_TOKEN=YOUR_API_TOKEN_HERE -
Install the ButterCMS SDK as a dependency:
终端窗口 npm install buttercms终端窗口 pnpm add buttercms终端窗口 yarn add buttercms -
Create a
buttercms.js
file in a newsrc/lib/
directory in your project:src/lib/buttercms.js import Butter from "buttercms";export const butterClient = Butter(import.meta.env.BUTTER_TOKEN);
这将使用你的 API 令牌对 SDK 进行身份验证,并将其导出以在你的项目中使用。
¥This authenticates the SDK using your API Token and exports it to be used across your project.
获取数据
标题部分 获取数据¥Fetching Data
要获取内容,请导入此客户端并使用其 retrieve
函数之一。
¥To fetch content, import this client and use one of its retrieve
functions.
在这个例子中,我们 检索集合 有三个字段:短文本 name
、数字 price
和所见即所得 description
。
¥In this example, we retrieve a collection that has three fields: a short text name
, a number price
, and a WYSIWYG description
.
---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
允许你渲染它。
¥The interface mirrors the field types. The WYSIWYG description
field loads as a string of HTML, and set:html
lets you render it.
同样,你可以 检索页面 并显示其字段:
¥Similarly, you can retrieve a page and display its fields:
---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>
官方资源
标题部分 官方资源¥Official Resources
-
ButterCMS 的 JavaScript 指南
社区资源
标题部分 社区资源¥Community Resources
- 添加你的!