Skip to content

ApostropheCMS 和 Astro

ApostropheCMS 是一个支持 Astro 页面编辑的内容管理系统。

¥ApostropheCMS is a content management system supporting on-page editing in Astro.

¥Integrating with Astro

在本节中,你将使用 Apostrophe 集成 将 ApostropheCMS 连接到 Astro。

¥In this section, you will use the Apostrophe integration to connect ApostropheCMS to Astro.

¥Prerequisites

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

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

  1. 按需渲染的 Astro 项目,安装了 Node.js 适配器 并配置了 output: 'server' - 如果你还没有 Astro 项目,我们的 安装指南 将立即帮助你启动并运行。

  2. 一个配置了名为 APOS_EXTERNAL_FRONT_KEY 的环境变量的 ApostropheCMS 项目 - 此环境变量可以设置为任何随机字符串。如果你还没有 ApostropheCMS 项目,安装指南 将快速设置一个。我们强烈建议使用 Apostrophe CLI 工具 来实现这一点。

¥Setting up project communication

你的 Astro 项目需要将 APOS_EXTERNAL_FRONT_KEY 环境变量设置为与 ApostropheCMS 项目中的值相同的值,以允许两者之间的通信。此共享密钥用作验证前端(Astro)和后端(ApostropheCMS)之间请求的一种方式。

¥Your Astro project needs to have an APOS_EXTERNAL_FRONT_KEY environment variable set to the same value as the one in your ApostropheCMS project to allow communication between the two. This shared key acts as a means to verify requests between the frontend (Astro) and the backend (ApostropheCMS).

使用以下变量在 Astro 项目的根目录中创建一个 .env 文件:

¥Create a .env file in the root of your Astro project with the following variable:

.env
APOS_EXTERNAL_FRONT_KEY='RandomStrongString'

你的根目录现在应该包含这个新文件:

¥Your root directory should now include this new file:

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

¥Installing dependencies

要将 Astro 与你的 ApostropheCMS 项目连接,请使用以下命令在你的 Astro 项目中安装官方 Apostrophe 集成,作为你首选的包管理器。

¥To connect Astro with your ApostropheCMS project, install the official Apostrophe integration in your Astro project using the command below for your preferred package manager.

终端窗口
npm install @apostrophecms/apostrophe-astro vite @astro/node

¥Configuring Astro

astro.config.mjs 文件中配置 apostrophe-astro 集成和 vite

¥Configure both the apostrophe-astro integration and vite in your astro.config.mjs file.

以下示例提供 Apostrophe 实例的基本 URL 和项目中文件夹的路径,以在 ApostropheCMS widgets页面模板 类型与你的 Astro 项目之间进行映射。它还配置 Vite 的服务器端渲染。

¥The following example provides the base URL of your Apostrophe instance and paths to folders in your project to map between the ApostropheCMS widgets and page template types and your Astro project. It also configures Vite’s server-side rendering.

astro.config.mjs
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';
import apostrophe from '@apostrophecms/apostrophe-astro';
import { loadEnv } from 'vite';
const env = loadEnv("", process.cwd(), 'APOS');
export default defineConfig({
output: 'server',
adapter: node({
mode: 'standalone'
}),
integrations: [
apostrophe({
aposHost: 'http://localhost:3000',
widgetsMapping: './src/widgets',
templatesMapping: './src/templates'
})
],
vite: {
ssr: {
// Do not externalize the @apostrophecms/apostrophe-astro plugin, we need
// to be able to use virtual: URLs there
noExternal: [ '@apostrophecms/apostrophe-astro' ],
},
define: {
'process.env.APOS_EXTERNAL_FRONT_KEY': JSON.stringify(env.APOS_EXTERNAL_FRONT_KEY),
'process.env.APOS_HOST': JSON.stringify(env.APOS_HOST)
}
}
});

有关完整的配置选项和说明,请参阅 apostrophe-astro 文档

¥For complete configuration options and explanations, see the apostrophe-astro documentation.

连接 ApostropheCMS 小部件到 Astro 组件

标题部分 连接 ApostropheCMS 小部件到 Astro 组件

¥Connecting ApostropheCMS widgets to Astro components

ApostropheCMS 小部件是可以添加到页面的结构化内容块,例如布局列、图片和文本块。你将需要为 Apostrophe 项目中的每个小部件创建一个 Astro 组件,以及一个文件来将这些组件映射到相应的 Apostrophe 小部件。

¥ApostropheCMS widgets are blocks of structured content that can be added to the page such as layout columns, images, and text blocks. You will need to create an Astro component for each widget in your Apostrophe project, plus a file to map those components to the corresponding Apostrophe widget.

src/widgets/ 处为你的 Astro 组件和映射文件 index.js 创建一个新文件夹。

¥Create a new folder at src/widgets/ for your Astro components and the mapping file, index.js.

位于此文件夹中的映射组件通过 Astro.props 接收包含小部件架构字段和任何自定义属性的 widget 属性。然后这些值可用于页面编辑。

¥Mapped components located in this folder receive a widget property containing your widget’s schema fields, and any custom props, through Astro.props. These values are then available for on-page editing.

以下示例显示了 RichTextWidget.astro 组件如何从其对应的 ApostropheCMS 小部件访问内容以允许在上下文中编辑:

¥The following example shows a RichTextWidget.astro component accessing the content from its corresponding ApostropheCMS widget to allow for in-context editing:

src/widgets/RichTextWidget.astro
---
const { widget } = Astro.props;
const { content } = widget;
---
<Fragment set:html={ content }></Fragment>

某些标准 Apostrophe 小部件(例如图片和视频)需要占位符,因为它们默认不包含可编辑内容。以下示例创建一个标准 ImageWidget.astro 组件,该组件有条件地将 src 值设置为小部件传递的 aposPlaceholder 图片的值、Astro 项目的后备图片或内容管理器使用 Apostrophe attachment 助手选择的图片:

¥Some standard Apostrophe widgets, such as images and videos, require placeholders because they do not contain editable content by default. The following example creates a standard ImageWidget.astro component that sets the src value conditionally to either the value of the aposPlaceholder image passed by the widget, a fallback image from the Astro project, or the image selected by the content manager using the Apostrophe attachment helper:

src/widgets/ImageWidget.astro
---
const { widget } = Astro.props;
const placeholder = widget?.aposPlaceholder;
const src = placeholder ?
'/images/image-widget-placeholder.jpg' :
widget?._image[0]?.attachment?._urls['full'];
---
<style>
.img-widget {
width: 100%;
}
</style>
<img class="img-widget" {src} />

有关更多示例,请参阅 astro-frontend 启动项目小部件示例

¥For more examples, see the astro-frontend starter project widget examples.

每个 .astro 组件都必须映射到 src/widgets/index.js 中相应的核心 Apostrophe 小部件。

¥Each .astro component must be mapped to the corresponding core Apostrophe widget in src/widgets/index.js.

以下示例将前两个组件添加到此文件:

¥The example below adds the previous two components to this file:

src/widgets/index.js
import RichTextWidget from './RichTextWidget.astro';
import ImageWidget from './ImageWidget.astro';
const widgetComponents = {
'@apostrophecms/rich-text': RichTextWidget,
'@apostrophecms/image': ImageWidget
};
export default widgetComponents;

请参阅 ApostropheCMS 文档 以了解标准、专业和自定义项目级小部件的命名约定

¥See the ApostropheCMS documentation for naming conventions for standard, pro, and custom-project-level widgets

项目目录现在应如下所示:

¥The project directory should now look like this:

  • Directorysrc/
    • Directorywidgets/
      • index.js
      • ImageWidget.astro
      • RichTextWidget.astro
  • .env
  • astro.config.mjs
  • package.json

¥Adding page types

与小部件非常相似,ApostropheCMS 项目中的任何页面类型模板都需要在 Astro 项目中具有相应的模板组件。你还需要一个将 Apostrophe 页面类型映射到各个组件的文件。

¥Much like widgets, any page type template in your ApostropheCMS project needs to have a corresponding template component in your Astro project. You will also need a file that maps the Apostrophe page types to individual components.

src/templates/ 处为你的 Astro 组件和映射文件 index.js 创建一个新文件夹。位于此文件夹中的映射组件通过 Astro.props 接收包含页面架构字段和任何自定义属性的 page 属性。这些组件还可以访问 AposArea 组件来渲染撇号区域。

¥Create a new folder at src/templates/ for your Astro components and the mapping file, index.js. Mapped components located in this folder receive a page property containing the schema fields of your page, and any custom props, through Astro.props. These components can also access an AposArea component to render Apostrophe areas.

以下示例显示了 HomePage.astro 组件如何从其对应的 home-page ApostropheCMS 页面类型渲染页面模板,包括一个名为 main 的区域架构字段:

¥The following example shows a HomePage.astro component rendering a page template from its corresponding home-page ApostropheCMS page type, including an area schema field named main:

src/templates/HomePage.astro
---
import AposArea from '@apostrophecms/apostrophe-astro/components/AposArea.astro';
const { page, user, query } = Astro.props.aposData;
const { main } = page;
---
<section class="bp-content">
<h1>{ page.title }</h1>
<AposArea area={main} />
</section>

每个 .astro 组件都必须映射到 src/templates/index.js 中相应的核心 Apostrophe 页面类型。

¥Each .astro component must be mapped to the corresponding core Apostrophe page type in src/templates/index.js.

以下示例将前一个 HomePage.astro 组件添加到此文件:

¥The example below adds the previous HomePage.astro component to this file:

src/templates/index.js
import HomePage from './HomePage.astro';
const templateComponents = {
'@apostrophecms/home-page': HomePage
};
export default templateComponents;

请参阅 ApostropheCMS 文档 以了解模板命名约定,包括特殊页面和片段页面类型。

¥See the ApostropheCMS documentation for template naming conventions, including special pages and piece page types.

项目目录现在应如下所示:

¥The project directory should now look like this:

  • Directorysrc/
    • Directorywidgets/
      • index.js
      • ImageWidget.astro
      • RichTextWidget.astro
    • Directorytemplates/
      • HomePage.astro
      • index.js
  • .env
  • astro.config.mjs
  • package.json

创建 […slug.astro] 组件并获取 Apostrophe 数据

标题部分 创建 […slug.astro] 组件并获取 Apostrophe 数据

¥Creating the […slug.astro] component and fetching Apostrophe data

由于 Apostrophe 负责将 URL 连接到内容,包括动态创建新内容和页面,因此你只需要一个顶层 Astro 页面组件:[...slug].astro 路由。

¥Since Apostrophe is responsible for connecting URLs to content, including creating new content and pages on the fly, you will only need one top-level Astro page component: the [...slug].astro route.

以下示例显示了最小的 [...slug].astro 组件:

¥The following example shows a minimal [...slug].astro component:

src/pages/[...slug].astro
---
import aposPageFetch from '@apostrophecms/apostrophe-astro/lib/aposPageFetch.js';
import AposLayout from '@apostrophecms/apostrophe-astro/components/layouts/AposLayout.astro';
import AposTemplate from '@apostrophecms/apostrophe-astro/components/AposTemplate.astro';
const aposData = await aposPageFetch(Astro.request);
const bodyClass = `myclass`;
if (aposData.redirect) {
return Astro.redirect(aposData.url, aposData.status);
}
if (aposData.notFound) {
Astro.response.status = 404;
}
---
<AposLayout title={aposData.page?.title} {aposData} {bodyClass}>
<Fragment slot="standardHead">
<meta name="description" content={aposData.page?.seoDescription} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
</Fragment>
<AposTemplate {aposData} slot="main"/>
</AposLayout>

请参阅 ApostropheCMS 文档 以获取其他模板选项,包括 AposTemplate 组件中可用的插槽。

¥See the ApostropheCMS documentation for additional templating options, including slots available in the AposTemplate component.

使用 Astro 和 ApostropheCMS 制作博客

标题部分 使用 Astro 和 ApostropheCMS 制作博客

¥Making a blog with Astro and ApostropheCMS

设置集成后,你现在可以使用 Astro 和 ApostropheCMS 创建博客。你的博客将使用 Apostrophe 片段(一种可以包含在任何页面上的独立内容类型)和片段页面类型(一种用于单独或集体显示这些片段的专用页面类型)。

¥With the integration set up, you can now create a blog with Astro and ApostropheCMS. Your blog will use an Apostrophe piece, a stand-alone content type that can be included on any page, and a piece page type, a specialized page type that is used for displaying those pieces either individually or collectively.

¥Prerequisites

  1. 一个安装了 Apostrophe CLI 工具的 ApostropheCMS 项目 - 你可以创建新项目或使用现有项目。但是,本教程将仅展示如何创建博客片段和片段页面类型。你必须独立集成任何其他现有项目代码。如果你尚未安装 CLI 工具,请查阅 Apostrophe CLI 安装说明
  2. 一个与 ApostropheCMS 集成的 Astro 项目 - 要从头开始创建项目,请参阅 与 Astro 集成 以获取有关如何设置集成的说明,或使用 astro-frontend 入门项目。

创建博客作品和作品页面类型

标题部分 创建博客作品和作品页面类型

¥Creating a blog piece and piece page type

要创建博客片段和片段页面类型以供显示,请在终端中导航到 ApostropheCMS 项目的根目录。使用 ApostropheCMS CLI 工具通过以下命令创建新的片段和片段页面类型:

¥To create your blog piece and piece page type for their display, navigate to the root of your ApostropheCMS project in your terminal. Use the ApostropheCMS CLI tool to create the new piece and piece page type with the following command:

终端窗口
apos add piece blog --page

这将在你的项目中创建两个新模块,一个用于博客片段类型,一个用于相应的片段页面类型。接下来,在代码编辑器中打开 ApostropheCMS 项目根目录中的 app.js 文件并添加新模块。

¥This will create two new modules in your project, one for the blog piece type and one for the corresponding piece page type. Next, open the app.js file at the root of your ApostropheCMS project in your code editor and add your new modules.

app.js
require('apostrophe')({
// other configuration options
modules: {
// other project modules
blog: {},
'blog-page': {}
}
});

blog-page 模块还需要添加到 @apostrophecms/page 模块 types 选项数组中,以便在页面创建模式中选择它。在你的 ApostropheCMS 项目中,打开 modules/@apostrophecms/page/index.js 文件并添加 blog-page

¥The blog-page module also needs to be added to the @apostrophecms/page module types option array so that it can be selected in the page creation modal. In your ApostropheCMS project, open the modules/@apostrophecms/page/index.js file and add the blog-page.

modules/@apostrophecms/page/index.js
module.exports = {
options: {
types: [
{
name: '@apostrophecms/home-page',
label: '主页'
},
// Any other project pages
{
name: 'blog-page',
label: 'Blog'
}
]
}
};

¥Creating the blog schema

在 ApostropheCMS 项目中,编辑器提供了一组用于添加内容的输入字段。这是一个简单博客文章的示例,它添加了三个输入字段,即 authorNamepublicationDatecontent 区域,内容管理员可以在其中添加多个小部件实例。在这种情况下,我们指定他们可以添加我们在 集成设置 期间创建的图片和富文本小部件。

¥In an ApostropheCMS project, editors are offered a set of input fields for adding content. Here is an example of a simple blog post that adds three input fields, an authorName, publicationDate and content area where content managers can add multiple widget instances. In this case, we are specifying they can add the image and rich-text widgets we created during the integration setup.

modules/blog/index.js
module.exports = {
extend: '@apostrophecms/piece-type',
options: {
label: 'Blog',
// Additionally add a `pluralLabel` option if needed.
},
fields: {
add: {
authorName: {
type: 'string',
label: 'Author'
},
publicationDate: {
type: 'date',
label: 'Publication date'
},
content: {
type: 'area',
label: 'Content',
options: {
widgets: {
'@apostrophecms/rich-text': {},
'@apostrophecms/image': {}
}
}
}
},
group: {
basics: {
label: 'Basic',
fields: [ 'authorName', 'publicationDate', 'content' ]
}
}
}
};

此时,来自 ApostropheCMS 项目的所有组件都已设置完毕。使用 npm run dev 从命令行启动本地站点,确保传入设置为你选择的字符串的 APOS_EXTERNAL_FRONT_KEY 环境变量:

¥At this point, all the components coming from the ApostropheCMS project are set up. Start the local site from the command line using npm run dev, making sure to pass in the APOS_EXTERNAL_FRONT_KEY environment variable set to your selected string:

终端窗口
APOS_EXTERNAL_FRONT_KEY='MyRandomString' npm run dev

¥Displaying the blog posts

要显示包含所有博客文章的页面,请在 Astro 项目的 src/templates 目录中创建一个 BlogIndex.astro 组件文件并添加以下代码:

¥To display a page with all the blog posts create a BlogIndex.astro component file in the src/templates directory of your Astro project and add the following code:

aposData prop 获取页面和片段数据后,此组件使用我们创建的博客片段架构中的两个字段以及 Apostrophe 添加到每个片段的 piece.titlepiece._url 创建标记。

¥After fetching both the page and pieces data from the aposData prop, this component creates markup using both fields from the blog piece schema we created, but also from the piece.title and piece._url that is added to each piece by Apostrophe.

src/templates/BlogIndex.astro
---
import dayjs from 'dayjs';
const { page, pieces } = Astro.props.aposData;
---
<section class="bp-content">
<h1>{ page.title }</h1>
<h2>Blog Posts</h2>
{pieces.map(piece => (
<h4>
Released On { dayjs(piece.publicationDate).format('MMMM D, YYYY') }
</h4>
<h3>
<a href={ piece._url }>{ piece.title }</a>
</h3>
<h4>{ piece.authorName }</h4>
))}
</section>

要显示单个博客文章,请在 Astro 项目 src/templates 文件夹中创建一个 BlogShow.astro 文件,其中包含以下代码:

¥To display individual blog posts, create a BlogShow.astro file in the Astro project src/templates folder with the following code:

此组件使用 <AposArea> 组件显示添加到 content 区域的任何小部件以及输入到同名字段中的 authorNamepublicationDate 内容。

¥This component uses the <AposArea> component to display any widgets added to the content area and the authorName and publicationDate content entered into the fields of the same names.

src/templates/BlogShow.astro
---
import AposArea from '@apostrophecms/apostrophe-astro/components/AposArea.astro';
import dayjs from 'dayjs';
const { page, piece } = Astro.props.aposData;
const { main } = piece;
---
<section class="bp-content">
<h1>{ piece.title }</h1>
<h3>Created by: { piece.authorName }
<h4>
Released On { dayjs(piece.publicationDate).format('MMMM D, YYYY') }
</h4>
<AposArea area={content} />
</section>

最后,这些 Astro 组件必须映射到相应的 ApostropheCMS 页面类型。打开 Astro 项目 src/templates/index.js 文件并修改它以包含以下代码:

¥Finally, these Astro components must be mapped to the corresponding ApostropheCMS page types. Open the Astro project src/templates/index.js file and modify it to contain the following code:

src/templates/index.js
import HomePage from './HomePage.astro';
import BlogIndexPage from './BlogIndexPage.astro';
import BlogShowPage from './BlogShowPage.astro';
const templateComponents = {
'@apostrophecms/home-page': HomePage,
'@apostrophecms/blog-page:index': BlogIndexPage,
'@apostrophecms/blog-page:show': BlogShowPage
};
export default templateComponents;

¥Creating blog posts

通过使用 ApostropheCMS 内容和管理工具创建这些帖子并发布至少一个索引页来显示它们,可以将博客文章添加到你的网站。

¥Adding blog posts to your site is accomplished by using the ApostropheCMS content and management tools to create those posts and by publishing at least one index page to display them.

在 Astro 开发服务器运行时,在浏览器预览中导航到位于 http://localhost:4321/login 的登录页面。使用 创建 ApostropheCMS 项目 期间添加的凭据以管理员身份登录。你的 ApostropheCMS 项目应该仍在运行。

¥With the Astro dev server running, navigate to the login page located at http://localhost:4321/login in your browser preview. Use the credentials that were added during the creation of the ApostropheCMS project to log in as an administrator. Your ApostropheCMS project should still be running.

登录后,浏览器将重定向到项目主页,并在顶部显示管理栏,用于编辑内容和管理项目。

¥Once you are logged in, your browser will be redirected to the home page of your project and will display an admin bar at the top for editing content and managing your project.

要添加你的第一篇博客文章,请单击管理栏中的 Blogs 按钮以打开博客文章创建模式。单击右上角的 New Blog 按钮将打开一个编辑模式,你可以在其中添加内容。content 区域字段允许你添加任意数量的图片和富文本小部件。

¥To add your first blog post, click on the Blogs button in the admin bar to open the blog piece creation modal. Clicking on the New Blog button in the upper right will open an editing modal where you can add content. The content area field will allow you to add as many image and rich text widgets as you desire.

你可以重复此步骤并添加任意数量的帖子。每次想要添加新帖子时,你也将遵循这些步骤。

¥You can repeat this step and add as many posts as you want. You will also follow these steps every time you want to add a new post.

要发布用于显示所有帖子的页面,请单击管理栏中的 Pages 按钮。从页面树模式单击 New Page 按钮。在右栏的 Type 下拉菜单中选择 Blog。为页面添加标题,然后单击 Publish and View。你只需执行一次此操作。

¥To publish a page for displaying all your posts, click on the Pages button in the admin bar. From the page tree modal click on the New Page button. In the Type dropdown in the right column select Blog. Add a title for the page and then click Publish and View. You will only need to do this once.

创建的任何新博客文章都将自动显示在此页面上。可以通过单击索引页上创建的链接来显示单个博客文章。

¥Any new blog posts that are created will be automatically displayed on this page. Individual blog posts can be displayed by clicking on the link created on the index page.

可以通过导航到帖子并单击管理栏中的 edit 直接在页面上编辑各个帖子的 content 区域。可以使用单击管理栏中的 Blogs 菜单项时打开的编辑模式编辑其他字段。

¥The content area of individual posts can be edited directly on the page by navigating to the post and clicking edit in the admin bar. Other fields can be edited by using the editing modal opened when clicking the Blogs menu item in the admin bar.

¥Deploying your site

要部署你的网站,你需要同时托管 Astro 和 ApostropheCMS 项目。

¥To deploy your website, you need to host both your Astro and ApostropheCMS projects.

对于 Astro,请访问我们的 部署指南 并按照你首选的托管服务提供商的说明进行操作。

¥For Astro, visit our deployment guides and follow the instructions for your preferred hosting provider.

对于 ApostropheCMS 项目,请按照我们的 托管指南 中有关你的托管类型的说明进行操作。最后,你需要向 Astro 项目提供一个 APOS_HOST 环境变量,以反映你的 ApostropheCMS 站点部署到的正确 URL。

¥For the ApostropheCMS project, follow the instructions for your hosting type in our hosting guide. Finally, you’ll need to supply an APOS_HOST environment variable to the Astro project to reflect the correct URL where your ApostropheCMS site has been deployed.

¥Official Resources

¥Community Resources

更多 CMS 指南

Astro 中文网 - 粤ICP备13048890号