预览
¥Preview
Page summary:
Preview connects the Content Manager to the front end so editors can see changes before publishing. In this documentation: configuration steps to set preview URLs.
使用预览功能,你可以直接从 Strapi 的管理面板预览前端应用。这有助于了解内容管理器编辑视图中的内容更新将如何影响最终结果。
¥With the Preview feature, you can preview your front end application directly from Strapi's admin panel. This is helpful to see how updates to your content in the Edit View of the Content Manager will affect the final result.
Live Preview available only with the CMS Growth and Enterprise plans.
config/admin
file

配置
¥Configuration
-
必须在你的
.env
文件中定义以下环境变量,用适当的值替换示例值:¥The following environment variables must be defined in your
.env
file, replacing example values with appropriate values:CLIENT_URL=https://your-frontend-app.com
PREVIEW_SECRET=your-secret-keyPREVIEW_SECRET
键是可选的,但在 Next.js 草稿模式下是必需的。¥The
PREVIEW_SECRET
key is optional but required with Next.js draft mode. -
应该已经创建并设置了你的 Strapi 项目的前端应用。
¥A front-end application for your Strapi project should be already created and set up.
配置组件
¥Configuration components
预览功能配置存储在 config/admin
文件 的 preview
对象中,由 3 个关键组件组成:
¥The Preview feature configuration is stored in the preview
object of the config/admin
file and consists of 3 key components:
激活标志
¥Activation flag
启用或禁用预览功能:
¥Enables or disables the preview feature:
// …
preview: {
enabled: true,
// …
}
// …
允许的来源
¥Allowed origins
控制哪些域可以访问预览:
¥Controls which domains can access previews:
// …
preview: {
enabled: true,
config: {
allowedOrigins: env("CLIENT_URL"), // Usually your frontend application URL
// …
}
}
// …
预览处理程序
¥Preview handler
管理预览逻辑和 URL 生成,如以下基本示例所示,其中 uid
是内容类型标识符(例如,api::article.article
或 plugin::my-api.my-content-type
):
¥Manages the preview logic and URL generation, as in the following basic example where uid
is the content-type identifier (e.g., api::article.article
or plugin::my-api.my-content-type
):
// …
preview: {
enabled: true,
config: {
// …
async handler(uid, { documentId, locale, status }) {
const document = await strapi.documents(uid).findOne({ documentId });
const pathname = getPreviewPathname(uid, { locale, document });
return `${env('PREVIEW_URL')}${pathname}`
},
}
}
// …
以下基本实现指南中给出了 URL 生成逻辑 的示例。
¥An example of URL generation logic in given in the following basic implementation guide.
预览草稿条目
¥Previewing draft entries
前端应用查询草稿或已发布内容的策略是特定于框架的。至少存在 3 种策略:
¥The strategy for the front end application to query draft or published content is framework-specific. At least 3 strategies exist:
-
使用查询参数,具有类似
/your-path?preview=true
的内容(例如,这是 Nuxt 的工作方式)¥using a query parameter, having something like
/your-path?preview=true
(this is, for instance, how Nuxt works) -
重定向到专用预览路由,如
/preview?path=your-path
(例如,这是 Next 的草稿模式 的工作方式)¥redirecting to a dedicated preview route like
/preview?path=your-path
(this is, for instance, how Next's draft mode works) -
或使用不同的域进行预览,如
preview.mysite.com/your-path
。¥or using a different domain for previews like
preview.mysite.com/your-path
.
当为你的内容类型启用 起草并发布 时,你还可以直接利用 Strapi 的 status
参数来处理预览处理程序中的逻辑,使用以下通用方法:
¥When Draft & Publish is enabled for your content-type, you can also directly leverage Strapi's status
parameter to handle the logic within the Preview handler, using the following generic approach:
async handler(uid, { documentId, locale, status }) {
const document = await strapi.documents(uid).findOne({ documentId });
const pathname = getPreviewPathname(uid, { locale, document });
if (status === 'published') {
// return the published version
}
// return the draft version
},
基本实现指南 中给出了使用 Next.js 草稿模式的更详细示例。
¥A more detailed example using the draft mode of Next.js is given in the basic implementation guide.
基本实现指南
¥Basic implementation guide
按照以下步骤将预览功能添加到你的内容类型。
¥Follow these steps to add Preview capabilities to your content types.
1. [Strapi] 创建预览配置
¥ [Strapi] Create the Preview configuration
创建一个新的文件 /config/admin.ts
(如果存在则更新它),具有以下基本结构:
¥Create a new file /config/admin.ts
(or update it if it exists) with the following basic structure:
export default ({ env }) => ({
// Other admin-related configurations go here
// (see docs.strapi.io/cms/configurations/admin-panel)
preview: {
enabled: true,
config: {
allowedOrigins: env('CLIENT_URL'),
async handler (uid, { documentId, locale, status }) => {
// Handler implementation coming in step 3
},
},
},
});
2. [Strapi] 添加 URL 生成逻辑
¥ [Strapi] Add URL generation logic
使用 getPreviewPathname
函数添加 URL 生成逻辑。以下示例取自 启动板 Strapi 演示应用:
¥Add the URL generation logic with a getPreviewPathname
function. The following example is taken from the Launchpad Strapi demo application:
// Function to generate preview pathname based on content type and document
const getPreviewPathname = (uid, { locale, document }): string => {
const { slug } = document;
// Handle different content types with their specific URL patterns
switch (uid) {
// Handle pages with predefined routes
case "api::page.page":
switch (slug) {
case "homepage":
return `/${locale}`; // Localized homepage
case "pricing":
return "/pricing"; // Pricing page
case "contact":
return "/contact"; // Contact page
case "faq":
return "/faq"; // FAQ page
}
// Handle product pages
case "api::product.product": {
if (!slug) {
return "/products"; // Products listing page
}
return `/products/${slug}`; // Individual product page
}
// Handle blog articles
case "api::article.article": {
if (!slug) {
return "/blog"; // Blog listing page
}
return `/blog/${slug}`; // Individual article page
}
default: {
return null;
}
}
};
// … main export (see step 3)
如果没有意义,某些内容类型不需要预览,因此默认情况返回 null
。例如,具有一些站点元数据的全局单一类型将没有匹配的前端页面。在这些情况下,处理程序函数应返回 null
,并且预览 UI 将不会显示在管理面板中。这是你为每种内容类型启用或禁用预览的方式。
¥Some content types don't need to have a preview if it doesn't make sense, hence the default case returning null
. A Global single type with some site metadata, for example, will not have a matching front-end page. In these cases, the handler function should return null
, and the preview UI will not be shown in the admin panel. This is how you enable or disable preview per content type.
3. [Strapi] 添加处理程序逻辑
¥ [Strapi] Add handler logic
创建完整配置,扩展在步骤 1 中创建的基本配置。使用在步骤 2 中创建的 URL 生成逻辑,添加适当的处理程序逻辑:
¥Create the complete configuration, expanding the basic configuration created in step 1. with the URL generation logic created in step 2., adding an appropriate handler logic:
const getPreviewPathname = (uid, { locale, document }): string => {
// … as defined in step 2
};
// Main configuration export
export default ({ env }) => {
// Get environment variables
const clientUrl = env("CLIENT_URL"); // Frontend application URL
const previewSecret = env("PREVIEW_SECRET"); // Secret key for preview authentication
return {
// Other admin-related configurations go here
// (see docs.strapi.io/cms/configurations/admin-panel)
preview: {
enabled: true, // Enable preview functionality
config: {
allowedOrigins: clientUrl, // Restrict preview access to specific domain
async handler(uid, { documentId, locale, status }) {
// Fetch the complete document from Strapi
const document = await strapi.documents(uid).findOne({ documentId });
// Generate the preview pathname based on content type and document
const pathname = getPreviewPathname(uid, { locale, document });
// Disable preview if the pathname is not found
if (!pathname) {
return null;
}
// Use Next.js draft mode passing it a secret key and the content-type status
const urlSearchParams = new URLSearchParams({
url: pathname,
secret: previewSecret,
status,
});
return `${clientUrl}/api/preview?${urlSearchParams}`;
},
},
},
};
};