跳转到内容

路由数据

当 Starlight 在你的文档中渲染一个页面时,它首先会创建一个路由数据对象来表示该页面上的内容。本指南解释了路由数据是如何生成的,如何使用它,以及如何自定义它来修改 Starlight 的默认行为。

有关可用属性的完整列表,请参阅“路由数据参考”

Starlight 路由数据是一个对象,包含了渲染单个页面所需的所有信息。它包括当前页面的信息以及从你的 Starlight 配置生成的数据。

Starlight 的所有组件都使用路由数据来决定每个页面要渲染什么。例如,siteTitle 字符串用于显示网站标题,而 sidebar 数组用于渲染全局侧边栏导航。

你可以在 Astro 组件中通过全局的 Astro.locals.starlightRoute 访问这些数据

example.astro
---
const { siteTitle } = Astro.locals.starlightRoute;
---
<p>The title of this site is “{siteTitle}</p>

例如,在构建组件覆盖以自定义显示内容时,这会非常有用。

Starlight 的路由数据开箱即用,无需任何配置。然而,对于高级用例,你可能需要为部分或所有页面自定义路由数据,以修改你的网站的显示方式。

这与组件覆盖的概念类似,但你不是修改 Starlight 如何渲染你的数据,而是修改 Starlight 渲染的数据本身。

当你希望以现有配置选项无法实现的方式修改 Starlight 处理数据的方式时,自定义路由数据会非常有用。

例如,你可能想要过滤侧边栏项目或为特定页面自定义标题。像这样的更改不需要修改 Starlight 的默认组件,只需要修改传递给这些组件的数据。

你可以使用一种特殊形式的“中间件”来自定义路由数据。这是一个在 Starlight 每次渲染页面时都会被调用的函数,它可以修改路由数据对象中的值。

  1. 使用 Starlight 的 defineRouteMiddleware() 工具创建一个新文件,并导出一个 onRequest 函数

    src/routeData.ts
    import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
    export const onRequest = defineRouteMiddleware(() => {});
  2. astro.config.mjs 中告诉 Starlight 你的路由数据中间件文件的位置

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';
    export default defineConfig({
    integrations: [
    starlight({
    title: 'My delightful docs site',
    routeMiddleware: './src/routeData.ts',
    }),
    ],
    });
  3. 更新你的 onRequest 函数以修改路由数据。

    你的中间件接收的第一个参数是 Astro 的 context 对象。它包含有关当前页面渲染的完整信息,包括当前 URL 和 locals

    在这个例子中,我们将通过在每个页面标题的末尾添加一个感叹号来使我们的文档更令人兴奋。

    src/routeData.ts
    import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
    export const onRequest = defineRouteMiddleware((context) => {
    // Get the content collection entry for this page.
    const { entry } = context.locals.starlightRoute;
    // Update the title to add an exclamation mark.
    entry.data.title = entry.data.title + '!';
    });

Starlight 也支持提供多个中间件。将 routeMiddleware 设置为路径数组以添加多个中间件处理程序

astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
integrations: [
starlight({
title: 'My site with multiple middleware',
routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
}),
],
});

要在执行你的代码之前等待堆栈中后面的中间件运行,你可以 await 作为第二个参数传递给你的中间件函数的 next() 回调。例如,这在等待插件的中间件运行后再进行更改时非常有用。

src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
export const onRequest = defineRouteMiddleware(async (context, next) => {
// Wait for later middleware to run.
await next();
// Modify route data.
const { entry } = context.locals.starlightRoute;
entry.data.title = entry.data.title + '!';
});