i18n for Svelte - Docs Github
Go to SSR Mode
Client Mode
We use localStorage for store and set locale
Since it not ssr, you might see the locale changes after reload
import { browser } from '$app/environment';
import { availableLocales, getLocale, setDefaultLocale, setLocale, t } from '$lib/lang/i18n.js';
// Svelte Kit wait for browser environment (not ssr)
if (browser) {
setDefaultLocale((localStorage.getItem('locale') as 'en' | 'id') || 'id');
}
const toggleLocale = () => {
const locale = getLocale();
const newLocale = locale === 'en' ? 'id' : 'en';
setLocale(newLocale);
localStorage.setItem('locale', newLocale);
};
en.json
{
"world": "World",
"hello_{name}": "Hello {name}",
"you_have_{count}_apple": "You have {count} apple",
"you_have_{count}_apple_plural": "You have {count} apples",
"you_have_{count}_item": "You have {count} item"
}
id.json
{
"world": "Dunia",
"hello_{name}": "Halo {name}",
"you_have_{count}_apple": "Kamu punya {count} apel",
"you_have_{count}_apple_plural": "Kamu punya {count} apel",
"you_have_{count}_item": "Kamu punya {count} item"
}
Default locale: id
Available locale: id, en
Current lang: id
{t('world')} Dunia
{t('hello_{name}', { name: 'Johan' })} Halo Johan
{t('hello_{name}', { name: t('world') })} Halo Dunia // Nested
{t('you_have_{count}_apple', { count: 1 })} Kamu punya 1 apel
{t('you_have_{count}_apple', { count: 12 })} Kamu punya 12 apel // Set suffix _plural: you_have_{count}_apple_plural
{t('you_have_{count}_item', { count: 1 })} Kamu punya 1 item
{t('you_have_{count}_item', { count: 12 })} Kamu punya 12 item // When you not set suffix _plural on lang json
{t('you_have_{count}_item')} Kamu punya {count} item // When you not set params
{t('h.w')} Halo Dunia // Nested
{t('h.c.w')} Halo C.Dunia // Nested Nested
{t('h.d_{x}', { x: 'Dino' })')} Halo Dunia Dino // Nested with params