Uso

Traducción Básica

Una vez configurado tu layout, simplemente usa getTranslations(namespace) en cualquier página para obtener una función de traducción tipada para un namespace específico.

src/pages/[lang]/index.astro
---
import { getTranslations } from "astro-intl";

// No need to call setRequestLocale here - it's already in the layout!
const tHero = getTranslations("hero");
const tNav  = getTranslations("nav");
---

<h1>{tHero("title")}</h1>
<p>{tHero("description")}</p>
<a href="/">{tNav("home")}</a>

Interpolación

Usa placeholders {curlyOpen}varName{curlyClose} en tus strings de traducción y pasa un objeto de valores como segundo argumento de t(). Tipos aceptados: string, number, boolean. Los valores faltantes o null/undefined mantienen el placeholder sin cambios.

en.json — message with variables
{
  "hero": {
    "greeting": "Hello, {name}!",
    "info": "You have {count} new messages"
  }
}
Component.astro — t() with values
---
const tHero = getTranslations("hero");
---

<p>{tHero("greeting", { name: "John" })}</p>
<!-- "Hello, John!" -->

<p>{tHero("info", { count: 5 })}</p>
<!-- "You have 5 new messages" -->

<p>{tHero("greeting")}</p>
<!-- "Hello, {name}!" — placeholder kept when no values -->

Traducción con Markup

Usa t.markup(key, tags) para interpolar etiquetas HTML dentro de un string de traducción. El objeto tags mapea nombres de etiquetas a funciones que reciben el contenido interno.

en.json — message with tags
{
  "hero": {
    "description": "A <bold>type-safe</bold> solution for <link>Astro</link>"
  }
}
Component.astro — t.markup()
---
const tHero = getTranslations("hero");
---

<p set:html={tHero.markup("description", {
  bold: (chunks) => `<strong>${chunks}</strong>`,
  link: (chunks) => `<a href="https://astro.build">${chunks}</a>`,
})} />

Markup + Interpolación

Combina interpolación de variables con reemplazo de tags pasando {curlyOpen} values, tags {curlyClose} a t.markup(). La interpolación se ejecuta primero, luego se procesan los tags.

en.json — variables + tags
{
  "hero": {
    "welcome": "Hello {name}, read our <link>docs</link> to get started"
  }
}
Component.astro — t.markup() with values
---
const tHero = getTranslations("hero");
---

<p set:html={tHero.markup("welcome", {
  values: { name: "John" },
  tags: {
    link: (chunks) => `<a href="/docs">${chunks}</a>`,
  }
})} />
<!-- "Hello John, read our <a href="/docs">docs</a> to get started" -->

t.raw() — Valores Sin Coerción

Usa t.raw(key) para acceder al valor de traducción sin coerción a string. Perfecto para arrays, objetos y números que necesitas en su tipo JavaScript nativo.

Accediendo a Arrays

Cuando tus traducciones contienen arrays, t.raw() los retorna como arrays JavaScript reales en lugar del string [object Object].

messages/en.json
{
  "features": ["Fast", "Lightweight", "Type-safe"]
}
Component.astro
---
import { getTranslations } from "astro-intl";
const t = getTranslations();

// Get raw array
const features = t.raw("features") as string[];
// features = ["Fast", "Lightweight", "Type-safe"]
---

<ul>
  &#123;features.map(feature => &lt;li&gt;&#123;feature&#125;&lt;/li&gt;)&#125;
&lt;/ul&gt;

Accediendo a Objetos

Los objetos se retornan tal cual, permitiéndote acceder a propiedades anidadas directamente sin parsing.

messages/en.json
{
  "theme": {
    "primary": "#3b82f6",
    "secondary": "#64748b"
  }
}
Component.astro
---
const theme = t.raw("theme") as { primary: string; secondary: string };
// theme = { primary: "#3b82f6", secondary: "#64748b" }
---

&lt;div style={`background: &#36;{theme.primary}`}&gt;...&lt;/div&gt;

Accediendo a Números

Los números permanecen como números — útil para cálculos o pasar a componentes que esperan valores numéricos.

messages/en.json
{
  "config": {
    "maxItems": 100,
    "timeout": 30
  }
}
Component.astro
---
const maxItems = t.raw("config.maxItems") as number;
// maxItems = 100 (number, not string)

// Can use for calculations
const limit = maxItems * 0.8; // 80
---
getTranslationsReact está obsoleto desde v2.0.0. Usa astro-intl/react en su lugar. Ver docs de React

Componentes React Deprecated

Usa getTranslationsReact(namespace) dentro de componentes React, luego llama a t.rich(key, tags) para interpolar nodos React.

MyComponent.tsx — t.rich()
import { getTranslationsReact } from "astro-intl";

export default function MyComponent() {
  const t = getTranslationsReact("hero");

  return (
    <p>
      {t.rich("description", {
        bold: (chunks) => <strong>{chunks}</strong>,
        link: (chunks) => <a href="https://astro.build">{chunks}</a>,
      })}
    </p>
  );
}