Ejemplos

Usando Namespaces

Los namespaces te permiten dividir archivos de traducción grandes en secciones lógicas. Pasa el nombre del namespace a getTranslations.

Multiple namespaces in one page
---
import { setRequestLocale, getTranslations } from "astro-intl";
import getRequestConfig from "../../i18n/request";

await setRequestLocale(Astro.url, getRequestConfig);

// Each call is scoped to its namespace
const tNav    = getTranslations("nav");
const tHero   = getTranslations("hero");
const tFooter = getTranslations("footer");
---

<nav>{tNav("home")}</nav>
<h1>{tHero("title")}</h1>
<footer>{tFooter("description")}</footer>

Interpolación

Reemplaza placeholders {curlyOpen}varName{curlyClose} en tus traducciones con valores dinámicos en tiempo de ejecución.

Interpolation with variables
---
import { setRequestLocale, getTranslations } from "astro-intl";
import getRequestConfig from "../../i18n/request";

await setRequestLocale(Astro.url, getRequestConfig);

const tHero = getTranslations("hero");
// en.json: { "hero": { "greeting": "Hello, {name}! You have {count} items." } }
---

<!-- Simple interpolation -->
<p>{tHero("greeting", { name: "John", count: 3 })}</p>
<!-- "Hello, John! You have 3 items." -->

<!-- Markup + interpolation combined -->
<p set:html={tHero.markup("welcome", {
  values: { name: "John" },
  tags: {
    link: (chunks) => `<a href="/docs">${chunks}</a>`,
  }
})} />
<!-- en.json: "welcome": "Hi {name}, check our <link>docs</link>" -->
<!-- Result: "Hi John, check our <a href="/docs">docs</a>" -->

Claves Type-Safe

Pasa el tipo de tus mensajes como genérico a getTranslations para obtener autocompletado completo y verificación de tipos en las claves de traducción.

Type-safe with generics
import type en from "../i18n/messages/en.json";

// Pass the type of your messages JSON
type HeroMessages = typeof en["hero"];

const tHero = getTranslations<HeroMessages>("hero");

// ✅ Autocomplete works — "title", "description", etc.
tHero("title");

// ❌ TypeScript error — key doesn't exist
tHero("nonExistentKey");

Leyendo el Locale Actual

Usa getLocale() en cualquier lugar después de que setRequestLocale haya sido llamado — por ejemplo para construir URLs con locale.

Locale-aware links
---
import { getLocale } from "astro-intl";

const locale = getLocale(); // "en" | "es"
---

<!-- Build locale-prefixed URLs -->
<a href={`/${locale}/docs`}>Documentation</a>
<a href={`/${locale}/about`}>About</a>