Skip to content

国际化 API 参考

Added in: astro@3.5.0

此模块提供功能来帮助你使用项目配置的语言环境创建 URL。

¥This module provides functions to help you create URLs using your project’s configured locales.

使用 i18n 路由为你的项目创建路由将取决于你设置的影响页面路由的某些配置值。使用这些功能创建路由时,请务必考虑你的个人设置:

¥Creating routes for your project with the i18n router will depend on certain configuration values you have set that affect your page routes. When creating routes with these functions, be sure to take into account your individual settings for:

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

¥Also, note that the returned URLs created by these functions for your defaultLocale will reflect your i18n.routing configuration.

有关功能和使用示例,查看我们的 i18n 路由指南

¥For features and usage examples, see our i18n routing guide.

¥Imports from astro:i18n

import {
getRelativeLocaleUrl,
getAbsoluteLocaleUrl,
getRelativeLocaleUrlList,
getAbsoluteLocaleUrlList,
getPathByLocale,
getLocaleByPath,
redirectToDefaultLocale,
redirectToFallback,
notFound,
middleware,
requestHasLocale,
} from 'astro:i18n';

类型:(locale: string, path?: string, options?: GetLocaleOptions) => string

¥Type: (locale: string, path?: string, options?: GetLocaleOptions) => string

使用此函数检索区域设置的相对路径。如果区域设置不存在,Astro 会抛出错误。

¥Use this function to retrieve a relative path for a locale. If the locale doesn’t exist, Astro throws an error.

---
import { getRelativeLocaleUrl } from 'astro:i18n';
getRelativeLocaleUrl("fr");
// returns /fr
getRelativeLocaleUrl("fr", "");
// returns /fr
getRelativeLocaleUrl("fr", "getting-started");
// returns /fr/getting-started
getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// returns /blog/fr-ca/getting-started
getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// returns /blog/fr_CA/getting-started
---

类型:(locale: string, path: string, options?: GetLocaleOptions) => string

¥Type: (locale: string, path: string, options?: GetLocaleOptions) => string

当 [site] 有值时,使用此函数检索语言环境的绝对路径。如果未配置 [site],则该函数返回相对 URL。如果区域设置不存在,Astro 会抛出错误。

¥Use this function to retrieve an absolute path for a locale when [site] has a value. If [site] isn’t configured, the function returns a relative URL. If the locale doesn’t exist, Astro throws an error.

src/pages/index.astro
---
import { getAbsoluteLocaleUrl } from 'astro:i18n';
// If `site` is set to be `https://example.com`
getAbsoluteLocaleUrl("fr");
// returns https://example.com/fr
getAbsoluteLocaleUrl("fr", "");
// returns https://example.com/fr
getAbsoluteLocaleUrl("fr", "getting-started");
// returns https://example.com/fr/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// returns https://example.com/blog/fr-ca/getting-started
getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// returns https://example.com/blog/fr_CA/getting-started
---

getRelativeLocaleUrlList()

标题部分 getRelativeLocaleUrlList()

类型:(path?: string, options?: GetLocaleOptions) => string[]

¥Type: (path?: string, options?: GetLocaleOptions) => string[]

getRelativeLocaleUrl 这样使用它可以返回所有语言环境的相对路径列表。

¥Use this like getRelativeLocaleUrl to return a list of relative paths for all the locales.

getAbsoluteLocaleUrlList()

标题部分 getAbsoluteLocaleUrlList()

类型:(path?: string, options?: GetLocaleOptions) => string[]

¥Type: (path?: string, options?: GetLocaleOptions) => string[]

getAbsoluteLocaleUrl 这样使用它可以返回所有语言环境的绝对路径列表。

¥Use this like getAbsoluteLocaleUrl to return a list of absolute paths for all the locales.

类型:(locale: string) => string

¥Type: (locale: string) => string

配置 自定义区域设置路径 时返回与一个或多个 codes 关联的 path 的函数。

¥A function that returns the path associated to one or more codes when custom locale paths are configured.

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

类型:(path: string) => string

¥Type: (path: string) => string

返回与区域设置 path 关联的 code 的函数。

¥A function that returns the code associated to a locale path.

astro.config.mjs
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
src/pages/index.astro
---
import { getLocaleByPath } from 'astro:i18n';
getLocaleByPath("french"); // returns "fr" because that's the first code configured
---

类型:(context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>

¥Type: (context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>

Added in: astro@4.6.0

返回重定向到配置的 defaultLocaleResponse 的函数。它接受可选的有效重定向状态代码。

¥A function that returns a Response that redirects to the defaultLocale configured. It accepts an optional valid redirect status code.

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);
}
})

类型:(context: APIContext, response: Response) => Promise<Response>

¥Type: (context: APIContext, response: Response) => Promise<Response>

Added in: astro@4.6.0

允许你在自己的中间件中使用 i18n.fallback configuration 的函数。

¥A function that allows you to use your i18n.fallback configuration in your own middleware.

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;
})

类型:(context: APIContext, response?: Response) => Promise<Response> | undefined

¥Type: (context: APIContext, response?: Response) => Promise<Response> | undefined

Added in: astro@4.6.0

在以下情况下,在路由中间件中使用此功能返回 404:

¥Use this function in your routing middleware to return a 404 when:

  • 当前路径不是根路径。例如 //<base>

  • URL 不包含语言环境

传递 Response 后,此函数发出的新 Response 将包含与原始响应相同的标头。

¥When a Response is passed, the new Response emitted by this function will contain the same headers of the original 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();
})

类型:(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler

¥Type: (options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler

Added in: astro@4.6.0

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

¥A function that allows you to programmatically create the Astro i18n middleware.

当你仍想使用默认的 i18n 逻辑,但只向网站添加一些例外情况时,这很有用。

¥This is useful when you still want to use the default i18n logic, but add only a few exceptions to your website.

middleware.js
import { middleware } from "astro:i18n";
import { sequence, defineMiddleware } from "astro:middleware";
const customLogic = defineMiddleware(async (context, next) => {
const response = await next();
// Custom logic after resolving the response.
// It's possible to catch the response coming from Astro i18n middleware.
return response;
});
export const onRequest = sequence(customLogic, middleware({
prefixDefaultLocale: true,
redirectToDefaultLocale: false
}))

类型:(context: APIContext) => boolean

¥Type: (context: APIContext) => boolean

Added in: astro@4.6.0

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

¥Checks whether the current URL contains a configured locale. Internally, this function will use 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 中文网 - 粤ICP备13048890号