The wedding website supports three languages: Spanish (default), English, and German. The i18n system is built with a simple, lightweight approach using JSON translation files and utility functions.
The src/i18n/index.ts file exports two key functions:
src/i18n/index.ts
import es from './es.json';import en from './en.json';import de from './de.json';const translations = { es, en, de };export type Lang = 'es' | 'en' | 'de';// Detect language from URL pathexport function getLang(url: URL): Lang { const path = url.pathname.split('/')[1]; if (path === 'en' || path === 'de') return path; return 'es'; // Default to Spanish}// Get translations for a specific languageexport function useTranslations(lang: Lang) { return translations[lang];}
Pages detect the language from the URL and pass it to components:
---// Spanish (default) - no lang detection neededimport Layout from '../layouts/Layout.astro';import Header from '../components/Header.astro';import SectionPrincipal from '../components/SectionPrincipal.astro';---<Layout title="Nuestra Historia - Alejandra & Alexander"> <Header /> <main> <SectionPrincipal /> </main></Layout>
Add a new JSON file in src/i18n/ (e.g., fr.json) with the same structure as existing files.
2
Update index.ts
src/i18n/index.ts
import es from './es.json';import en from './en.json';import de from './de.json';import fr from './fr.json'; // Add importconst translations = { es, en, de, fr }; // Add to objectexport type Lang = 'es' | 'en' | 'de' | 'fr'; // Add to typeexport function getLang(url: URL): Lang { const path = url.pathname.split('/')[1]; if (path === 'en' || path === 'de' || path === 'fr') return path; return 'es';}
3
Create page directory
Create src/pages/fr/index.astro following the pattern of /en and /de pages.
4
Update header component
Add the new language link to the language switcher in Header.astro.