跳转到内容

API 参考

Astro global 在 .astro 文件的所有上下文中都可用。它具有以下功能:

Astro.glob() 可以在静态网站 setup 中加载本地文件:

src/components/my-component.astro
---
const posts = await Astro.glob('../pages/post/*.md'); // 返回位于 ./src/pages/post/*.md 的数组并存储在常量 posts 中
---
<div>
{posts.slice(0, 3).map((post) => (
<article>
<h1>{post.frontmatter.title}</h1>
<p>{post.frontmatter.description}</p>
<a href={post.frontmatter.url}>Read more</a>
</article>
))}
</div>

.glob() 只需要一个参数:你想导入的本地文件相对 glob URL。它是异步的并返回数组,这个数组包含匹配文件的导出内容。

.glob() 不接受使用变量或字符串进行插值,因为它们不是静态可分析的。(参见故障排查以了解解决方法)。这是因为 Astro.glob() 是 Vite 的 import.meta.glob() 的包装器。

Markdown 文件有以下接口:

export interface MarkdownInstance<T extends Record<string, any>> {
/* 在此文件的 YAML frontmatter 中指定的任何数据 */
frontmatter: T;
/* 该文件的文件路径 */
file: string;
/* 该文件的渲染路径 */
url: string | undefined;
/* 渲染此文件内容的 Astro 组件 */
Content: AstroComponent;
/* 返回该文件中 h1...h6 元素数组的函数 */
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
}

你可以选择使用 TypeScript 泛型指定 frontmatter 变量类型:

---
interface Frontmatter {
title: string;
description?: string;
}
const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');
---
<ul>
{posts.map(post => <li>{post.frontmatter.title}</li>)}
</ul>

Astro 文件具有以下接口:

export interface AstroInstance {
/* 此文件的文件路径 */
file: string;
/* 此文件的 URL(如果它在 pages 目录中)*/
url: string | undefined;
default: AstroComponent;
}

其他文件可能有各种不同的接口,但如果你不知道文件类型包含什么,那么 Astro.glob() 可以接受 TypeScript 泛型。

---
interface CustomDataFile {
default: Record<string, any>;
}
const data = await Astro.glob<CustomDataFile>('../data/**/*.js');
---

Astro.props 是一个包含任何作为组件属性传递的值的对象。.md.mdx 文件的布局组件接收作为参数的 frontmatter 值。

src/components/Heading.astro
---
const { title, date } = Astro.props;
---
<div>
<h1>{title}</h1>
<p>{date}</p>
</div>
src/pages/index.astro
---
import Heading from '../components/Heading.astro';
---
<Heading title="我的第一篇文章" date="09 Aug 2022" />
进一步了解关于 Markdown 和 MDX 布局 如何处理 props 的内容。
了解如何为你的 props 添加 TypeScript 类型定义 的内容。

Astro.params 是一个包含与此请求匹配的动态路由段的值的对象。

在静态构建中,这将是 getStaticPaths() 返回的params,用于预渲染动态路由.。

在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。

src/pages/posts/[id].astro
---
export function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
const { id } = Astro.params;
---
<h1>{id}</h1>

另见:params

Astro.request 是标准的 Request 对象。它可以用来获取请求的 urlheadersmethod,甚至是 body。可以使用 new URL(Astro.request.url) 来获得链接对象。

<p>Received a {Astro.request.method} request to "{Astro.request.url}".</p>
<p>Received request headers: <code>{JSON.stringify(Object.fromEntries(Astro.request.headers))}</code>

另见:Astro.url

Astro.response 是标准的 ResponseInit 对象,它具有以下结构:

  • status:响应的状态码,例如 200
  • statusText:响应状态码与之相对应的状态信息,例如 OK
  • headers:一个能让你为响应设置 HTTP 头部的 Headers 实例。

所以 Astro.response 也用于设置页面响应的 statusstatusTextheaders

---
if(condition) {
Astro.response.status = 404;
Astro.response.statusText = 'Not found';
}
---

或者设置 header:

---
Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;');
---

添加于: astro@1.4.0

Astro.cookies 包含用于在服务端渲染模式下读取和操作 cookie 的工具方法。

类型: (key: string, options?: CookieGetOptions) => AstroCookie

获取 AstroCookie 对象形式的 cookie,该对象包含value和用于将 cookie 转换为非字符串类型的工具方法。

类型: (key: string) => boolean

用于判断 cookie 是否存在。如果这个 cookie 已经通过Astro.cookies.set()设置,这将返回 true,否则它将检查 Astro.request 中的 cookies。

类型: (key: string, value: string | number | boolean | object, options?: CookieSetOptions) => void

将 cookie key 设置为给定的值。这将试图把 cookie 的值转换为一个字符串。选项提供了设置 cookie 功能的方法,例如 maxAgehttpOnly

类型: (key: string, options?: CookieDeleteOptions) => void

将 Cookie 标记为已删除。一旦 Cookie 被删除,Astro.cookies.has() 将返回 falseAstro.cookies.get() 将返回一个值为 undefinedAstroCookie。删除 Cookie 时可用的选项包括:domainpathhttpOnlysameSitesecure

类型: () => Iterator<string>

获取将与响应一起发送的 Set-Cookie 的 header 的值。

通过 Astro.cookies.get() 获取 cookie 返回一个 AstroCookie 类型。它具有以下结构。

类型: string | undefined

cookie 的原始字符串值。

类型: () => Record<string, any>

通过 JSON.parse() 解析 cookie 值,返回一个对象。如果 cookie 值不是有效的 JSON,则抛出异常。

类型: () => number

将 cookie 值解析为数字。如果不是有效数字,则返回 NaN。

类型: () => boolean

转换 cookie 的值为 boolean 类型。

添加于: astro@4.1.0

获取 cookie 允许通过 CookieGetOptions 接口指定选项:

类型: (value: string) => string

允许自定义如何将 cookie 反序列化为值。

添加于: astro@4.1.0

通过 Astro.cookies.set() 设置 cookie, 允许传入 CookieSetOptions 来自定义 cookie 如何被序列化。

类型: string

Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.

指定域。如果未设置域,则大多数客户端将解释为应用于当前域。

类型: Date

指定 cookie 过期日期。

类型: boolean

如果为 true,则客户端将无法访问该 Cookie。

类型: number

以秒为单位指定 cookie 有效的时间。

类型: string

指定应用 cookie 的域的子路径。

类型: boolean | 'lax' | 'none' | 'strict'

指定 SameSite cookie header 的值。

类型: boolean

如果为 true,则该 Cookie 仅在 https 网站上设置。

类型: (value: string) => string

允许自定义 cookie 序列化方式。

Astro.redirect() 允许你重定向到另一个页面。

页面(而不是子组件)必须 return Astro.redirect() 的结果,以便重定向发生。

src/pages/account.astro
---
import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// 如果用户未登录,则将其重定向到登录页面
if (!isLoggedIn(cookie)) {
return Astro.redirect('/login');
}
---

当前页面的标准链接

添加于: astro@1.0.0-rc

URL对象,由当前 Astro.request.url 的链接字符串值构成。对于与请求的链接的个别属性进行交互是有用的,如路径名和起源。

相当于做 new URL(Astro.request.url)

<h1>当前链接是:{Astro.url}</h1>
<h1>当前链接路径名是:{Astro.url.pathname}</h1>
<h1>当前链接源是:{Astro.url.origin}</h1>

你也可以使用 Astro.url 来创建新的链接,并把它作为参数传给 new URL()

src/pages/index.astro
---
// 示例:使用你的生产域名构建一个规范的URL
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// 示例:使用你目前的域名构建一个用于 SEO meta 标签的URL
const socialImageURL = new URL('/images/preview.png', Astro.url);
---
<link rel="canonical" href={canonicalURL} />
<meta property="og:image" content={socialImageURL} />

添加于: astro@1.0.0-rc

指定请求的 IP 地址。这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。

---
const ip = Astro.clientAddress;
---
<div>你的 IP 地址是:<span class="address">{ ip }</span></div>

Astro.site 返回根据 Astro 配置中的 site 生成的 URL。如果未定义 Astro 配置中的 siteAstro.site 也不会被定义。

添加于: astro@1.0.0

Astro.generator 是个便捷方法,它可以添加与你当前 Astro 版本一致的 <meta name="generator"> 标签。它遵循的格式是 "Astro v1.x.x"

<html>
<head>
<meta name="generator" content={Astro.generator} />
</head>
<body>
<footer>
<p><a href="https://astro.build">{Astro.generator}</a> 构建</p>
</footer>
</body>
</html>

Astro.slots 包含修改 Astro 组件插槽的工具函数。

类型:(slotName: string) => boolean

你可以使用 Astro.slots.has() 检查特定插槽名称的内容是否存在。当你想要包装插槽内容,但只想在使用插槽时呈现包装器元素时,这会很有用。

src/pages/index.astro
---
---
<slot />
{Astro.slots.has('more') && (
<aside>
<h2>More</h2>
<slot name="more" />
</aside>
)}

类型:(slotName: string, args?: any[]) => Promise<string>

你可以使用 Astro.slots.render() 将插槽的内容异步渲染为 HTML 字符串。

---
const html = await Astro.slots.render('default');
---
<Fragment set:html={html} />

Astro.slots.render() 还可以接受第二个参数:一个参数数组,该参数数组将被转发给任何函数子组件。这对于自定义实用程序组件很有用。

举个例子,这个 <Shout /> 组件将它的 message 属性转换为大写,并将其传递给默认插槽:

src/components/Shout.astro
---
const message = Astro.props.message.toUpperCase();
let html = '';
if (Astro.slots.has('default')) {
html = await Astro.slots.render('default', [message]);
}
---
<Fragment set:html={html} />

作为 <Shout /> 的子级传递的回调函数将会接收到大写的 message 参数:

src/pages/index.astro
---
import Shout from "../components/Shout.astro";
---
<Shout message="slots!">
{(message) => <div>{message}</div>}
</Shout>
<!-- 渲染成 <div>SLOTS!</div> -->

Astro.self 允许 Astro 组件被递归调用。这使得你可以通过在组件模板中使用 <Astro.self> 从自身内部渲染 Astro 组件。这对遍历大型数据存储和嵌套数据结构很有帮助。

NestedList.astro
---
const { items } = Astro.props;
---
<ul class="nested-list">
{items.map((item) => (
<li>
<!-- 如果有嵌套的数据结构,将渲染 `<Astro.self>` -->
<!-- 并可以通过递归调用来传递参数 -->
{Array.isArray(item) ? (
<Astro.self items={item} />
) : (
item
)}
</li>
))}
</ul>

然后,这个组件可以这样用:

---
import NestedList from './NestedList.astro';
---
<NestedList items={['A', ['B', 'C'], 'D']} />

之后将会渲染这样的 HTML:

<ul class="nested-list">
<li>A</li>
<li>
<ul class="nested-list">
<li>B</li>
<li>C</li>
</ul>
</li>
<li>D</li>
</ul>

Astro.locals 是一个对象,包含来自中间件的 context.locals对象的任何值。使用该对象可访问中间件在你的 .astro 文件中返回的数据。

src/pages/Orders.astro
---
const title = Astro.locals.welcomeTitle();
const orders = Array.from(Astro.locals.orders.entries());
---
<h1>{title}</h1>
<ul>
{orders.map(order => {
return <li>{ /* 每单都有收获 */ }</li>
})}
</ul>

Astro.preferredLocale 是一个代表当前用户的首选语言环境的计算出的值。

它是通过检查 i18n.locales 数组中配置的语言环境和用户浏览器通过头部 Accept-Language 指定的语言环境来计算的。如果不存在匹配项则该值为 undefined

这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。

Astro.preferredLocaleList 是一个同时被浏览器请求并且你的网站也支持的语言环境的数组。它是一个由你的网站和你的访客共同支持的语言环境的列表。

如果浏览器请求的语言环境没有在你的网站中被支持,那么该值为 []:你不支持你的访客的任何首选语言环境。

如果浏览器没有指定任何首选语言环境,那么该值将是 i18n.locales:你支持的所有语言环境都将被同等视为访客倾向的语言环境。

这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。

从当前 URL 使用你的 locales 配置中指定的语法计算出的语言环境。如果 URL 不包含 /[locale]/ 前缀,则该值将默认为 i18n.defaultLocale

端点函数接收一个上下文对象作为第一个参数。它与许多 Astro 全局属性相似。

endpoint.json.ts
import type { APIContext } from 'astro';
export function GET(context: APIContext) {
// ...
}

context.params 是一个对象,其中包含与此请求匹配的动态路由段的值。

在静态构建中,这将是用于预渲染动态路由getStaticPaths() 返回的 params

在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。

src/pages/posts/[id].json.ts
import type { APIContext } from 'astro';
export function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
export function GET({ params }: APIContext) {
return new Response(
JSON.stringify({ id: params.id }),
);
}

另见:params

context.props 是一个对象,其中包含从 getStaticPaths() 传递的任何 props。由于在为 SSR 构建时不使用 getStaticPaths(),因此 context.props 仅在静态构建中可用。

src/pages/posts/[id].json.ts
import type { APIContext } from 'astro';
export function getStaticPaths() {
return [
{ params: { id: '1' }, props: { author: 'Blu' } },
{ params: { id: '2' }, props: { author: 'Erika' } },
{ params: { id: '3' }, props: { author: 'Matthew' } }
];
}
export function GET({ props }: APIContext) {
return new Response(
JSON.stringify({ author: props.author }),
);
}

另见:通过props传递数据

一个标准的 Request 对象。它可以用来获取请求的 urlheadersmethod 甚至是 body

import type { APIContext } from 'astro';
export function GET({ request }: APIContext) {
return new Response(`Hello ${request.url}`);
}

另见:Astro.request

context.cookies 包含用于读取和操作 cookie 的工具。

另见:Astro.cookies

context.url 是一个 URL 对象,它是从当前 context.request.url URL 字符串值构造的。

另见:Astro.url

指定请求的 IP 地址。此属性仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。

import type { APIContext } from 'astro';
export function GET({ clientAddress }: APIContext) {
return new Response(`Your IP address is: ${clientAddress}`);
}

另见:Astro.clientAddress

context.site 返回一个由 Astro 配置中的 site 生成的 URL。如果未定义,则将返回从 localhost 生成的 URL。

另见:Astro.site

context.generator 是一个方便的方法,用于指示项目正在运行的 Astro 版本。它遵循 "Astro v1.x.x" 的格式。

src/pages/site-info.json.ts
import type { APIContext } from 'astro';
export function GET({ generator, site }: APIContext) {
const body = JSON.stringify({ generator, site });
return new Response(body);
}

另见:Astro.generator

context.redirect() 返回一个 Response 对象,允许你重定向到另一个页面。此函数仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。

import type { APIContext } from 'astro';
export function GET({ redirect }: APIContext) {
return redirect('/login', 302);
}

另见:Astro.redirect()

context.locals 是一个对象,用于在请求的生命周期内存储和访问任意信息。

中间件函数可以读写context.locals的值:

src/middleware.ts
import type { MiddlewareHandler } from 'astro';
export const onRequest: MiddlewareHandler = ({ locals }, next) => {
if (!locals.title) {
locals.title = "Default Title";
}
return next();
}

API 端点只能从 context.locals中读取信息:

src/pages/hello.ts
import type { APIContext } from 'astro';
export function get({ locals }: APIContext) {
return new Response(locals.title); // "默认标题"
}

另见:Astro.locals

如果页面在文件名中使用动态参数,该组件将需要导出一个 getStaticPaths() 函数。

必须要有该函数,因为 Astro 是静态站点生成器。这意味着整个网站是预构建的。如果 Astro 不知道在构建时生成什么页面,你的用户在访问你的网站时就看不到它。

---
export async function getStaticPaths() {
return [
{ params: { /* 必需 */ }, props: { /* 可选 */ } },
{ params: { ... } },
{ params: { ... } },
// ...
];
}
---
<!-- 你的 HTML 模板在这里 -->

getStaticPaths() 函数应该返回对象数组,以确定哪些路径会被 Astro 预渲染。

每个返回对象的 params 键都会告诉 Astro 要构建什么路由。返回参数必须映射到你的组件文件路径中定义的动态参数和其余参数。

params 被编码到链接中,所以只能由字符串作为值。每个 params 对象的值必须与页面名称中使用的参数一致。

比如说有 src/pages/posts/[id].astro 页面。如果你从这个页面导出 getStaticPaths 并返回以下的路由:

---
export async function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
const { id } = Astro.params;
---
<h1>{id}</h1>

然后 Astro 会在构建时静态地生成 posts/1posts/2posts/3

为了给每个生成的页面传递额外的数据,你也可以在每个返回的路径对象上设置 props 值。与 params 不同的是,props 没有被编码到链接中,所以并不局限于字符串。

例如,假设你根据从远程 API 获取的数据来生成页面。你可以将完整的数据对象传递给 getStaticPaths 中的页面组件。

---
export async function getStaticPaths() {
const data = await fetch('...').then(response => response.json());
return data.map((post) => {
return {
params: { id: post.id },
props: { post },
};
});
}
const { id } = Astro.params;
const { post } = Astro.props;
---
<h1>{id}: {post.name}</h1>

你也可以传递普通数组,这在生成或缓存已知路径列表时可能会有帮助。

---
export async function getStaticPaths() {
const posts = [
{id: '1', category: "astro", title: "API Reference"},
{id: '2', category: "react", title: "Creating a React Counter!"}
];
return posts.map((post) => {
return {
params: { id: post.id },
props: { post }
};
});
}
const {id} = Astro.params;
const {post} = Astro.props;
---
<body>
<h1>{id}: {post.title}</h1>
<h2>Category: {post.category}</h2>
</body>

然后 Astro 将在构建时使用 pages/posts/[id].astro 中的页面组件静态地生成 posts/1posts/2。页面可以使用 Astro.props 引用这些数据。

分页是 Astro 通过 paginate() 函数原生支持网站的常见用例。paginate() 将自动生成数组,从getStaticPaths()返回,为分页集合的每个页面创建一个 URL。页面编号将作为参数传递,而页面数据将作为page道具传递。

export async function getStaticPaths({ paginate }) {
// 用 fetch()、Astro.glob() 等加载你的数据
const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`);
const result = await response.json();
const allPokemon = result.results;
// 返回包含分页的所有帖子的路由集合
return paginate(allPokemon, { pageSize: 10 });
}
// 如果设置正确,现在页面已经具备了渲染单页所需的一切参数(见下一节)。
const { page } = Astro.props;

paginate():假定文件名为 [page].astro[...page].astropage 参数将是链接中的页数。

  • /posts/[page].astro:会产生 /posts/1/posts/2/posts/3 等链接。
  • /posts/[...page].astro:将产生 /posts/posts/2 /posts/3 等链接。

paginate() 函数具有以下参数:

  • pageSize - 每页显示的项目数
  • params - 用于创建动态路由的附加参数
  • props - 在每个页面上可用的附加属性

分页会给每个渲染的页面传递 page 参数,代表分页集合中的单页数据。这包括你分页的数据(page.data)以及该页的元数据(page.urlpage.startpage.endpage.total 等)。这些元数据对诸如“下一页”按钮或“显示 100 个中前十个”的信息很有用。

类型: Array

data() 中返回当前页面数据数组。

类型: number

当前页第一个项目的索引,从 0 开始(例如,如果 pageSize: 25,第一页该值未 0,第二页为25,以此类推)。

类型: number

当前页面最后一条数据的索引。

类型: number

每个页面有多少条数据。

类型: number

所有数据的总数量。

类型: number

当前页码,从 1 开始。

类型: number

总页数。

类型: string

获取当前页面的链接(对规范链接很有用)。

类型: string | undefined

获取上一页链接(如果在首页,将是undefined)。

类型: string | undefined

获取下一页链接(如果没有更多的页面,将是undefined)。

所有 ESM 模块都包含 import.meta 属性。Astro 基于 Vite 增加了 import.meta.env

import.meta.env.SSR 可以用来了解何时在服务器渲染。有时你可能想要不同的逻辑,例如,某个组件应该只在客户端渲染:

export default function () {
return import.meta.env.SSR ? <div class="spinner"></div> : <FancyComponent />;
}

getImage()函数旨在生成用于在 HTML 之外的其他地方所使用的图像,例如在 API 路由 中。它还允许你创建自定义的 <Image /> 组件。

getImage() 函数接受一个选项对象,其中包含与 Image 组件相同的属性(除了 alt)。

---
import { getImage } from "astro:assets";
import myBackground from "../background.png"
const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---
<div style={`background-image: url(${optimizedBackground.src});`}></div>

它返回了一个包含了如下属性的对象:

{
options: {...} // 被传递的原始参数
src: "https//..." // 生成图片的路径
attributes: {...} // 额外的 HTML 属性,用于渲染图像(如宽度、高度、样式等)
}

内容集合(astro:content

段落标题 内容集合(astro:content)

添加于: astro@2.0.0

内容集合提供了 API 来配置和查询 src/content/ 中的 Markdown 或 MDX 文档。有关功能和用法示例,请参考内容集合指南

defineCollection() 是一个用于在 src/content/config.* 文件中配置集合的工具函数。

src/content/config.ts
import { z, defineCollection } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
permalink: z.string().optional(),
}),
});
// 将定义的集合公开给 Astro
// 通过 `collections` 导出
export const collections = { blog };

这个函数接受以下属性:

添加于: astro@2.5.0

类型: 'content' | 'data'
默认: 'content'

type 是一个字符串,用于定义存储在集合中的条目的类型:

  • 'content' - 用于内容创作格式,如 Markdown (.md)、MDX (.mdx) 或 Markdoc (.mdoc)
  • 'data' - 用于 JSON (.json) 或 YAML (.yaml) 等纯数据格式

类型:TSchema extends ZodType

schema 是一个可选的 Zod 对象,用于配置集合的文档 frontmatter 的类型和形状。每个值必须使用 Zod 验证器

有关示例请参考 内容集合指南

Type: (collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>

在内容配置中使用 reference() 函数来定义从一个集合到另一个集合的关系或 “引用”。该函数接受一个集合名称,并验证内容前置事项或数据文件中指定的条目标识符。

此示例定义了从博客作者到 “作者 “集合的引用,以及到同一 “博客 “集合的相关文章数组的引用:

import { defineCollection, reference, z } from 'astro:content';
const blog = defineCollection({
type: 'content',
schema: z.object({
// 通过 "id "从 "作者 "集合中引用单个作者
author: reference('authors'),
// 按 "slug "从 "blog "集合中引用相关帖子数组
relatedPosts: z.array(reference('blog')),
})
});
const authors = defineCollection({
type: 'data',
schema: z.object({ /* ... */ })
});
export const collections = { blog, authors };

有关示例请参考 内容集合指南.

类型:(collection: string, filter?: (entry: CollectionEntry<collection>) => boolean) => CollectionEntry<collection>[]

getCollection() 是一个函数,用于通过集合名称检索内容集合条目列表。

默认情况下,它返回集合中的所有项目,并接受可选的 filter 函数来缩小条目属性。这允许你根据 idslug 或 frontmatter 值(通过 data 对象)查询集合中的某些项目。

---
import { getCollection } from 'astro:content';
// 获取 `src/content/blog/` 中的所有条目
const allBlogPosts = await getCollection('blog');
// 仅返回 frontmatter 中 `draft: true` 的条目
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
---

有关示例请参考 内容集合指南 以获取示例用法。

添加于: astro@2.5.0

Types:

  • (collection: string, contentSlugOrDataId: string) => CollectionEntry<collection>
  • ({ collection: string, id: string }) => CollectionEntry<collection>
  • ({ collection: string, slug: string }) => CollectionEntry<collection>

getEntry() 是一个函数,可通过集合名称和条目 id (对于 type: 'data' 集合)或条目 slug (对于 type: 'content' 集合)检索单个集合条目。getEntry()也可用于获取引用条目,以访问databodyrender()属性:

---
import { getEntry } from 'astro:content';
// 得到 `src/content/blog/enterprise.md`
const enterprisePost = await getEntry('blog', 'enterprise');
// 得到 `src/content/captains/picard.yaml`
const picardProfile = await getEntry('captains', 'picard');
// 得到 the profile referenced by `data.captain`
const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);
---

有关内容集合的示例,请参考 查询集合条目.

添加于: astro@2.5.0

Types:

  • (Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>
  • (Array<{ collection: string, slug: string }>) => Array<CollectionEntry<collection>>

getEntries() 是一个从同一集合中检索多个集合条目的函数。这对于返回引用条目的数组访问其关联的databodyrender()属性非常有用。

---
import { getEntries } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// 获取由 `data.relatedPosts` 引用的相关帖子
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---

类型:(collection: string, slug: string) => CollectionEntry<collection>

getEntryBySlug() 是一个函数,用于通过集合名称和条目 slug 检索单个集合条目。

---
import { getEntryBySlug } from 'astro:content';
const enterprise = await getEntryBySlug('blog', 'enterprise');
---

有关示例请参考 内容集合指南 以获取示例用法。

getCollection()getEntryBySlug() 函数都会返回 CollectionEntry 类型的条目。这个类型可以从 astro:content 中获取:

import type { CollectionEntry } from 'astro:content';

CollectionEntry<TCollectionName> 类型是一个对象,具有以下值。 TCollectionName 是你正在查询的集合的名称(例如 CollectionEntry<'blog'>)。

适用于: type: 'content' and type: 'data' 集合

示例类型:

  • content collections: 'entry-1.md' | 'entry-2.md' | ...
  • data collections: 'author-1' | 'author-2' | ...

一个使用相对于 src/content/[collection] 的文件路径的唯一 ID。根据集合条目文件路径枚举所有可能的字符串值。请注意,类型: 'content' 的集合在其 ID 中包含文件扩展名,而定义为 type: 'data' 的集合则不包含。

适用于: type: 'content' and type: 'data' 集合

示例类型: 'blog' | 'authors' | ...

src/content/` 下顶级文件夹的名称,条目位于该文件夹中。该名称用于在模式和查询函数中引用集合。

适用于: type: 'content' and type: 'data' 集合

类型:CollectionSchema<TCollectionName>

一个从集合模式推断出的 frontmatter 属性对象(参考 defineCollection())。如果没有配置模式,则默认为 any

适用于: 仅仅 type: 'content' 集合

示例类型: 'entry-1' | 'entry-2' | ...

可用于 Markdown 或 MDX 文档的 URL 标头。默认为不含文件扩展名的 “id”,但可以通过在文件的 frontmatter 中设置slug属性来覆盖。

适用于:type: 'content' 集合

类型:string

一个包含 Markdown 或 MDX 文档原始未编译的 body 的字符串。

适用于:type: 'content' 集合

类型:() => Promise<RenderedEntry>

一个用于编译给定的 Markdown 或 MDX 文档以进行渲染的函数。它返回以下属性:

---
import { getEntryBySlug } from 'astro:content';
const entry = await getEntryBySlug('blog', 'entry-1');
const { Content, headings, remarkPluginFrontmatter } = await entry.render();
---

有关示例请参考 内容集合指南 以获取示例用法。

astro:content 模块也导出了以下类型,供你在 Astro 项目中使用:

这是一个在 src/content/config.* 文件中定义的所有集合名称的字符串联合类型。当定义一个可以接受任何集合名称的通用函数时,这个类型很有用。

import type { CollectionKey, getCollection } from 'astro:content';
async function getCollection(collection: CollectionKey) {
return getCollection(collection);
}

一个在 src/content/config.* 文件中定义的所有 type: 'content' 集合名称的字符串联合类型。

一个在 src/content/config.* 文件中定义的所有 type: 'data' 集合名称的字符串联合类型。

defineCollectionschema 函数形状中所使用的 context 对象。当为多个集合构建可重用的模式时,这个类型很有用。

它包括了以下属性:

import type { SchemaContext } from 'astro:content';
export const imageSchema = ({ image }: SchemaContext) =>
z.object({
image: image(),
description: z.string().optional(),
});
const blog = defineCollection({
type: 'content',
schema: ({ image }) => z.object({
title: z.string(),
permalink: z.string().optional(),
image: imageSchema({ image })
}),
});

中间件(astro:middleware

段落标题 中间件(astro:middleware)

添加于: astro@2.6.0

中间件使你能拦截请求和响应,并在每次渲染页面或端点时动态注入行为。有关功能和用法示例,请参考中间件指南

一个在 src/middleware.js 里的必须导出的函数,它将在每次渲染页面或端点时被调用。它接受两个可选参数:contextnext()onRequest() 必须返回一个 Response:要么直接返回,要么通过调用 next() 返回。

src/middleware.js
export function onRequest (context, next) {
// 拦截一个请求的响应数据
// 可选修改响应
// 直接返回一个 Response 对象,或者调用 `next()` 的结果
return next();
};

一个拦截(读取和修改)一个 RequestResponse 或调用链中的“下一个(next)”中间件并返回一个 Response 的函数。例如,这个函数可以修改响应的 HTML 主体。

这是 onRequest() 的可选参数,并且可能会提供中间件返回的所需 Response

一个接受中间件函数作为参数的函数,它将按照它们传递的顺序执行它们。

src/middleware.js
import { sequence } from "astro:middleware";
async function validation(_, next) {...}
async function auth(_, next) {...}
async function greeting(_, next) {...}
export const onRequest = sequence(validation, auth, greeting);

一个底层 API,用于创建一个 APIContext 以传递给 Astro 中间件的 onRequest() 函数。

此函数可以由集成/适配器用于执行 Astro 中间件。

一个底层 API,它接受任何值并尝试返回它的序列化版本(一个字符串)。如果该值无法序列化,该函数将抛出一个运行时错误。

添加于: astro@3.5.0

此模块提供了一些函数,帮助你使用项目配置的语言环境设置创建 URL。

使用 i18n 路由为你的项目创建路由将依赖于你设置的某些配置值,这些值会影响你的页面路由。使用这些函数创建路由时,请确保考虑到你的个人设置,包括:

另外,请注意,这些函数为你的 defaultLocale 创建的返回 URL 将反映你的 i18n.routing 配置。

有关功能和使用示例,请参阅我们的 i18n 路由指南

getRelativeLocaleUrl(locale: string, path?: string, options?: GetLocaleOptions): string

使用此函数来检索一个语言环境的相对路径。如果该语言环境不存在,Astro 会抛出一个错误。

---
getRelativeLocaleUrl("fr");
// 返回 /fr
getRelativeLocaleUrl("fr", "");
// 返回 /fr
getRelativeLocaleUrl("fr", "getting-started");
// 返回 /fr/getting-started
getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// 返回 /blog/fr-ca/getting-started
getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// 返回 /blog/fr_CA/getting-started
---

getAbsoluteLocaleUrl(locale: string, path: string, options?: GetLocaleOptions): string

当 [site] 配置了值时,使用这个函数来检索一个语言环境的绝对路径。如果 [site] 没有被配置,该函数将返回一个相对 URL。如果语言环境不存在,Astro 会抛出一个错误。

src/pages/index.astro
---
// 如果 `site` 被设置为 `https://example.com`
getAbsoluteLocaleUrl("fr");
// 返回 https://example.com/fr
getAbsoluteLocaleUrl("fr", "");
// 返回 https://example.com/fr
getAbsoluteLocaleUrl("fr", "getting-started");
// 返回 https://example.com/fr/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// 返回 https://example.com/blog/fr-ca/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// 返回 https://example.com/blog/fr_CA/getting-started
---

getRelativeLocaleUrlList()

段落标题 getRelativeLocaleUrlList()

getRelativeLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]

像使用 getRelativeLocaleUrl 那样使用此函数,返回所有语言环境的相对路径列表。

getAbsoluteLocaleUrlList()

段落标题 getAbsoluteLocaleUrlList()

getAbsoluteLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]

像使用 getAbsoluteLocaleUrl 那样使用此函数,返回所有语言环境的绝对路径列表。

getPathByLocale(locale: string): string

当配置了自定义语言环境路径时,此函数返回与一个或多个 codes 关联的 path

astro.config.mjs
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
src/pages/index.astro
---
getPathByLocale("fr"); // 返回 "french"
getPathByLocale("fr-CA"); // 返回 "french"
---

getLocaleByPath(path: string): string

此函数返回与语言环境 path 关联的 code

astro.config.mjs
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
src/pages/index.astro
---
getLocaleByPath("french"); // 返回 "fr",因为这是首个配置的代码
---

redirectToDefaultLocale(context: APIContext, statusCode?: ValidRedirectStatus): Promise<Response>

添加于: astro@4.6.0

此函数返回一个 Response,将重定向到配置的 defaultLocale。它接受一个可选的有效重定向状态码。

middleware.js
import { defineMiddleware } from "astro:middleware";
import { redirectToDefaultLocale } from "astro:i18n";
export const onRequest = defineMiddleware((context, next) => {
if (context.url.pathname.startsWith("/about")) {
return next();
} else {
return redirectToDefaultLocale(context, 302);
}
})

redirectToFallback(context: APIContext, response: Response): Promise<Response>

添加于: astro@4.6.0

此函数允许你在自己的中间件中使用你的 i18n.fallback 配置

middleware.js
import { defineMiddleware } from "astro:middleware";
import { redirectToFallback } from "astro:i18n";
export const onRequest = defineMiddleware(async (context, next) => {
const response = await next();
if (response.status >= 300) {
return redirectToFallback(context, response)
}
return response;
})

notFound(context: APIContext, response: Response): Promise<Response>

添加于: astro@4.6.0

当以下情况发生时,在你的路由中间件中使用此函数来返回一个 404 错误:

  • 当前路径不是根路径。例如://<base>
  • URL 中不包含语言环境代码

当传递了一个 Response,由此函数发出的新 Response 将包含原始响应的相同头信息。

middleware.js
import { defineMiddleware } from "astro:middleware";
import { notFound } from "astro:i18n";
export const onRequest = defineMiddleware((context, next) => {
const pathNotFound = notFound(context);
if (pathNotFound) {
return pathNotFound;
}
return next();
})

middleware(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean })

添加于: astro@4.6.0

此函数允许你以编程方式创建 Astro i18n 中间件。

当你仍然想要使用默认的 i18n 逻辑,但只在你的网站添加少数例外时,这个功能非常有用。

middleware.js
import { middleware } from "astro:i18n";
import { sequence, defineMiddleware } from "astro:middleware";
const customLogic = defineMiddleware(async (context, next) => {
const response = await next();
// 在这里解析响应后的自定义逻辑。
// 可以捕获来自 Astro i18n 中间件的响应。
return response;
});
export const onRequest = sequence(customLogic, middleware({
prefixDefaultLocale: true,
redirectToDefaultLocale: false
}))

requestHasLocale(context: APIContext): boolean

添加于: astro@4.6.0

检查当前 URL 是否包含已配置的语言环境代码。在内部,此函数将使用 APIContext#url.pathname

middleware.js
import { defineMiddleware } from "astro:middleware";
import { requestHasLocale } from "astro:i18n";
export const onRequest = defineMiddleware(async (context, next) => {
if (requestHasLocale(context)) {
return next();
}
return new Response("Not found", { status: 404 });
})

Astro 包括几个内置的组件供你在你的项目中使用。在 .astro 文件中可以通过 import {} from 'astro:components'; 引用所有的内置组件。

---
import { Code } from 'astro:components';
---
<!-- 使用语法凸显部分 JavaScript 代码-->
<Code code={`const foo = 'bar';`} lang="js" />
<!-- 可选:定制你的主题 -->
<Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" />
<!-- 可选:启用文字包装 -->
<Code code={`const foo = 'bar';`} lang="js" wrap />
<!-- Optional: Output inline code. -->
<p>
<Code code={`const foo = 'bar';`} lang="js" inline />
will be rendered inline.
</p>

该组件在构建时为代码块提供语法高亮(不包括客户端 JavaScript)。该组件由 Shiki 驱动,它支持所有流行的主题语言。另外,你可以通过给 themelang 传递自定义主题和语言分别添加它们。

一个与 set:* 指令 一起使用的组件,用于渲染 HTML 内容而不添加任何额外的包裹元素。

src/components/SetHtml.astro
---
const htmlString = '<p>Raw HTML content</p>';
---
<Fragment set:html={htmlString} />

请参见在 Astro 语法中使用片段的更多信息。

要安装 Prism 高亮器组件,需要先安装 @astrojs/prism 包:

Terminal window
npm i @astrojs/prism
---
import { Prism } from '@astrojs/prism';
---
<Prism lang="js" code={`const foo = 'bar';`} />

这个组件通过应用 Prism 的 CSS 类为代码块提供特定语言的语法高亮。注意,你需要提供 Prism 的 CSS 样式表(或用自己的),以启用语法高亮!参见 Prism 配置部分了解更多细节。

参见 Prism 支持的语言列表,在那里你可以找到一种语言的对应别名。而且,你也可以用 lang="astro" 来展示 Astro 代码块!

src/components/MyComponent.astro
---
// 导入图像组件和图片
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---
<!-- `alt` 在 Image 组件中是必需的属性 -->
<Image src={myImage} alt="A description of my image." />
<!-- 输出 -->
<!-- Image 组件已经过优化,并且对应的属性也被强制使用。 -->
<img
src="/_astro/my_image.hash.webp"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>
  • src(必需的)
  • alt(必需的)
  • width 和 height(对 public/ 和远程图像而言是必需的)
  • format
  • quality
  • densities
  • widths

除了上述属性之外,<Image /> 组件还接受 HTML <img> 标签接受的所有属性。

详见图像指南

添加于: astro@3.3.0

使用内置的 <Picture /> Astro 组件来展示具有多种格式和(或)尺寸的响应式图像。

src/pages/index.astro
---
import { Picture } from 'astro:assets';
import myImage from "../assets/my_image.png"; // 图像的分辨率为 1600x900
---
<!-- 在图片组件上 `alt` 属性是必需的 -->
<Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." />
<!-- 输出 -->
<picture>
<source srcset="/_astro/my_image.hash.avif" type="image/avif" />
<source srcset="/_astro/my_image.hash.webp" type="image/webp" />
<img
src="/_astro/my_image.hash.png"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>
</picture>

详见图像指南

<Picture /> 接受 <Image /> 组件的所有属性,以及以下属性:

一个图像格式的数组,用于 <source> 标签。默认情况下,它被设置为 ['webp']

用于作为 <img> 标签的回退值的格式。对于静态图像,默认为 .png;对于动画图像,默认为 .gif;对于 SVG 文件,默认为 .svg

一个被添加到 <picture> 标签的属性对象。使用该属性可将属性应用于外部的 <picture> 元素本身。除了用于图像转换的属性外,直接应用于 <Picture /> 组件的属性将应用于内部的 <img> 元素。

一个通用组件,用于呈现 内容集合条目 的内容。

首先,使用 getCollection()getEntry() 查询一个或多个条目。然后,entry.render() 函数可以返回 <Content /> 组件,以供在 .astro 文件模板中使用。

src/pages/render-example.astro
---
import { getEntry } from 'astro:content';
const entry = await getEntry('blog', 'post-1');
const { Content } = await entry.render();
---
<p>Published on: {entry.data.published.toDateString()}</p>
<Content />

在每个希望应用视图过渡动画的页面上,通过导入并将 <ViewTransitions /> 路由组件添加到 <head> 中,来选择使用单个页面上的视图过渡动画。

src/pages/index.astro
---
import { ViewTransitions } from 'astro:transitions';
---
<html lang="en">
<head>
<title>My Homepage</title>
<ViewTransitions />
</head>
<body>
<h1>Welcome to my website!</h1>
</body>
</html>

查看更多关于如何控制路由器和向页面元素和组件添加过渡动画指令的信息。

---
import { Debug } from 'astro:components';
const serverObject = {
a: 0,
b: "string",
c: {
nested: "object"
}
}
---
<Debug {serverObject} />

这个组件提供了无需 JavaScript 在客户端检查数值的方法。