국제화 API 참조
추가된 버전:
astro@3.5.0
이 모듈은 프로젝트에 구성된 로케일을 사용하여 URL을 생성하는 데 도움이 되는 함수를 제공합니다.
i18n 라우터를 사용하여 프로젝트에 대한 경로를 생성하는 것은 페이지 경로에 영향을 주는 특정 구성 값에 따라 달라집니다. 이러한 함수를 사용하여 경로를 생성할 때 다음에 대한 개별 설정을 고려해야 합니다.
또한 defaultLocale에 대해 이러한 함수에서 반환된 URL은 i18n.routing 구성을 반영합니다.
기능 및 사용 예시는 i18n 라우팅 가이드를 참조하세요.
astro:i18n에서 가져오기
섹션 제목: “astro:i18n에서 가져오기”import { getRelativeLocaleUrl, getAbsoluteLocaleUrl, getRelativeLocaleUrlList, getAbsoluteLocaleUrlList, getPathByLocale, getLocaleByPath, redirectToDefaultLocale, redirectToFallback, notFound, middleware, requestHasLocale, normalizeTheLocale, pathHasLocale, toCodes, toPaths } from 'astro:i18n';getRelativeLocaleUrl()
섹션 제목: “getRelativeLocaleUrl()”타입: (locale: string, path?: string, options?: GetLocaleOptions) => string
이 함수를 사용하여 로케일의 상대 경로를 검색합니다. 해당 로케일이 존재하지 않으면 Astro는 오류를 발생시킵니다.
---import { getRelativeLocaleUrl } from 'astro:i18n';
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()
섹션 제목: “getAbsoluteLocaleUrl()”타입: (locale: string, path?: string, options?: GetLocaleOptions) => string
[site]의 값이 존재할 때 로케일의 절대 경로를 검색하려면 이 함수를 사용하세요. [site]가 구성되지 않은 경우 함수는 상대 URL을 반환합니다. 해당 로케일이 존재하지 않으면 Astro는 오류를 발생시킵니다.
---import { getAbsoluteLocaleUrl } from 'astro:i18n';
// `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()”타입: (path?: string, options?: GetLocaleOptions) => string[]
모든 로케일에 대한 상대 경로 목록을 반환하려면 getRelativeLocaleUrl처럼 이 함수를 사용하세요.
getAbsoluteLocaleUrlList()
섹션 제목: “getAbsoluteLocaleUrlList()”타입: (path?: string, options?: GetLocaleOptions) => string[]
모든 로케일에 대한 절대 경로 목록을 반환하려면 getAbsoluteLocaleUrl처럼 이 함수를 사용하세요.
getPathByLocale()
섹션 제목: “getPathByLocale()”타입: (locale: string) => string
사용자 정의 로케일 경로가 구성된 경우 하나 이상의 codes와 연결된 path를 반환하는 함수입니다.
export default defineConfig({ i18n: { locales: ["es", "en", { path: "french", codes: ["fr", "fr-BR", "fr-CA"] }] }})---import { getPathByLocale } from 'astro:i18n';
getPathByLocale("fr"); // "french" 반환getPathByLocale("fr-CA"); // "french" 반환---getLocaleByPath()
섹션 제목: “getLocaleByPath()”타입: (path: string) => string
로케일 path와 연관된 code를 반환하는 함수입니다.
export default defineConfig({ i18n: { locales: ["es", "en", { path: "french", codes: ["fr", "fr-BR", "fr-CA"] }] }})---import { getLocaleByPath } from 'astro:i18n';
getLocaleByPath("french"); // 구성된 첫 번째 code이기 때문에 "fr"을 반환합니다.---redirectToDefaultLocale()
섹션 제목: “redirectToDefaultLocale()”타입: (context: APIContext, statusCode?: ValidRedirectStatus) => Promise<Response>
astro@4.6.0
i18n.routing이 "manual"로 설정된 경우에만 사용할 수 있습니다.
구성된 defaultLocale로 리디렉션되는 Response를 반환하는 함수입니다. 유효한 리디렉션 상태 코드를 선택적으로 허용합니다.
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()
섹션 제목: “redirectToFallback()”타입: (context: APIContext, response: Response) => Promise<Response>
astro@4.6.0
i18n.routing이 "manual"로 설정된 경우에만 사용할 수 있습니다.
자체 미들웨어에서 i18n.fallback 구성을 사용할 수 있게 해주는 함수입니다.
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()
섹션 제목: “notFound()”타입: (context: APIContext, response?: Response) => Promise<Response> | undefined
astro@4.6.0
i18n.routing이 "manual"로 설정된 경우에만 사용할 수 있습니다.
다음과 같은 경우 라우팅 미들웨어에서 이 함수를 사용하여 404를 반환합니다.
- 현재 경로가 루트가 아닌 경우. 예를 들어
/또는/<base> - URL에 로케일이 포함되어 있지 않은 경우
Response가 전달되면 이 함수에서 내보낸 새 Response에는 원래 응답과 동일한 헤더가 포함됩니다.
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()
섹션 제목: “middleware()”타입: (options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler
astro@4.6.0
i18n.routing이 "manual"로 설정된 경우에만 사용할 수 있습니다.
Astro i18n 미들웨어를 프로그래밍 방식으로 생성할 수 있는 함수입니다.
이는 기본 i18n 로직을 계속 사용하고 싶지만 웹 사이트에 몇 가지 예외만 추가하려는 경우에 유용합니다.
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()
섹션 제목: “requestHasLocale()”타입: (context: APIContext) => boolean
astro@4.6.0
i18n.routing이 "manual"로 설정된 경우에만 사용할 수 있습니다.
현재 URL에 구성된 로케일이 포함되어 있는지 확인합니다. 내부적으로 이 함수는 APIContext#url.pathname을 사용합니다.
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 });})normalizeTheLocale()
섹션 제목: “normalizeTheLocale()”타입: (locale: string) => string
주어진 로케일의 밑줄(_)을 하이픈(-)으로 바꾸고 소문자 버전으로 반환합니다.
---import { normalizeTheLocale } from "astro:i18n";
normalizeTheLocale("it_VT") // `it-vt`를 반환합니다.// 현재 로케일이 `"pt-PT"`라고 가정할 때:normalizeTheLocale(Astro.currentLocale) // `pt-pt`를 반환합니다.---pathHasLocale()
섹션 제목: “pathHasLocale()”타입: (path: string) => boolean
astro@4.6.0
주어진 경로에 구성된 로케일이 포함되어 있는지 확인합니다.
이것은 URL 경로의 로케일에 의존하는 i18n 유틸리티를 사용하기 전에 오류를 방지하는 데 유용합니다.
export default defineConfig({ i18n: { locales: [ { codes: ["it-VT", "it"], path: "italiano" }, "es" ] }})---import { pathHasLocale } from "astro:i18n";
pathHasLocale("italiano"); // `true`를 반환합니다.pathHasLocale("es"); // `true`를 반환합니다.pathHasLocale('/es/blog/'); // `true`를 반환합니다.pathHasLocale("it-VT"); // `false`를 반환합니다.---toCodes()
섹션 제목: “toCodes()”타입: (locales: Locales) => string[]
astro@4.0.0
구성에서 정의된 각 로케일에 대해 구성된 로케일 코드를 검색합니다. 로케일에 여러 코드가 연결된 경우에는 배열에 첫 번째 코드만 추가됩니다.
export default defineConfig({ i18n: { locales: [ { codes: ["it-VT", "it"], path: "italiano" }, "es" ] }})---import { i18n } from "astro:config/client";import { toCodes } from "astro:i18n";
toCodes(i18n!.locales); // ["it-VT", "es"]---toPaths()
섹션 제목: “toPaths()”타입: (locales: Locales) => string[]
astro@4.0.0
구성에서 정의된 각 로케일에 대해 구성된 로케일 경로를 검색합니다.
export default defineConfig({ i18n: { locales: [ { codes: ["it-VT", "it"], path: "italiano" }, "es" ] }})---import { i18n } from "astro:config/client";import { toPaths } from "astro:i18n";
toPaths(i18n!.locales); // ["italiano", "es"]---