Translations and variables

Continue from Quick start. Keep the same configuration and replace the messages and page with the following examples.

Messages with variables and sections

A variable reserves a place for a value. A namespace groups related keys in an object such as nav. Keep the same structure in both languages.

src/i18n/messages/en.json
{
  "greeting": "Hello, {name}!",
  "nav": {
    "home": "Home"
  }
}
src/i18n/messages/es.json
{
  "greeting": "Hola, {name}!",
  "nav": {
    "home": "Inicio"
  }
}

Translate in your page

getTranslations() reads from the root; getTranslations('nav') scopes keys to nav. Initialize the language in the page before translating. A layout used inside a page cannot initialize that page’s frontmatter retroactively.

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

export function getStaticPaths() {
  return [{ params: { lang: "en" } }, { params: { lang: "es" } }];
}

await setRequestLocale(Astro.url);
const t = getTranslations();
const tNav = getTranslations("nav");
---

<h1>{t("greeting", { name: "Ana" })}</h1>
<a href={`/${Astro.params.lang}/`}>{tNav("home")}</a>

Accepted values

Variables accept string, number and boolean. If you omit a variable or pass null/undefined, its placeholder stays in the text. For HTML tags and components, continue to Rich text.