Localization
Introduction
The @plinthjs/localization package lets your application speak more than one language. You keep the text of your interface in message files, one set per locale, and ask a Translator for a line by key. The translator handles the details that make translation awkward in practice: placeholders inside sentences, a fallback language for missing lines, plural forms that differ between languages, and message files that live on disk.
The translator is a plain object. Nothing is global, so you create one, register it in your container if you want to share it, and pass it around like any other service.
pnpm add @plinthjs/localizationCreating a Translator
A Translator needs an active locale and a fallback. The fallback is used for any line that is missing in the active locale.
import { Translator } from '@plinthjs/localization'
const translator = new Translator({ locale: 'en', fallback: 'en' })
translator.addMessages('en', {
auth: { failed: 'These credentials do not match our records.' },
welcome: 'Welcome, :Name!',
})
translator.get('auth.failed') // => 'These credentials do not match our records.'
translator.get('welcome', { name: 'taylor' }) // => 'Welcome, Taylor!'Lines are addressed by dot-separated keys. auth.failed walks into the auth bag and reads failed. Asking for a key that does not exist returns the key itself, which makes a missing translation visible on the page instead of throwing.
translator.get('does.not.exist') // => 'does.not.exist'
translator.has('auth.failed') // => true
translator.has('does.not.exist') // => falseDefining Lines
There are three ways to add lines to a locale. They can be mixed and are merged.
addMessages(locale, bag) takes a nested object. Calling it again deep-merges into what is already there.
translator.addMessages('es', {
auth: { failed: 'Estas credenciales no coinciden con nuestros registros.' },
})addLines(locale, lines) takes flat records with dotted keys, which is convenient for small sets.
translator.addLines('en', { 'mail.greeting': 'Hello :name' })
translator.get('mail.greeting', { name: 'Al' }) // => 'Hello Al'addStrings(locale, strings) registers JSON-style translations where the key is the sentence in your source language. These keys are matched literally, so they may contain dots, commas and punctuation.
translator.addStrings('fr', { 'I love programming.': "J'adore programmer." })
translator.get('I love programming.', {}, 'fr') // => "J'adore programmer."Use JSON strings for short interface text where writing a sentence is clearer than inventing a key, and grouped keys for text you want to organize or reuse. When the active locale has no string for a sentence, the sentence itself is returned, which is usually the right fallback for this style.
Replacing Placeholders
A :name token in a line is replaced from the replacements object you pass as the second argument. The casing of the token controls the casing of the value: :name inserts it as given, :Name capitalizes the first letter, and :NAME upper-cases it. The brace form {name} inserts the value as given.
translator.addLines('en', { shout: 'HEY :NAME, {name} again' })
translator.get('shout', { name: 'ada' }) // => 'HEY ADA, ada again'
translator.get('welcome', { name: 'taylor' }) // => 'Welcome, Taylor!'Replacement values may be strings or numbers. Longer names are substituted first, so :name_full is not damaged by a :name replacement.
Locales and Fallbacks
getLocale() and setLocale() read and change the active locale. You usually set it once per request, from a header, a cookie or the signed-in user's preference.
translator.setLocale('fr')
translator.getLocale() // => 'fr'Every lookup method also takes an optional locale as its last argument, which overrides the active locale for that call: translator.get('auth.failed', {}, 'es').
When a key is missing in the active locale, the translator tries the fallback locale, then returns the key. The fallback is applied per key, so a partly translated locale still shows complete pages.
const t = new Translator({ locale: 'fr', fallback: 'en' })
t.addMessages('en', { greeting: 'Hello' })
t.get('greeting') // => 'Hello'The fallback can also be an ordered list. Each locale is tried in turn.
const t = new Translator({ locale: 'pt', fallback: ['es', 'en'] })
t.addMessages('en', { a: 'EN a', b: 'EN b' })
t.addMessages('es', { a: 'ES a' })
t.get('a') // => 'ES a'
t.get('b') // => 'EN b'
t.getFallbackChain() // => ['es', 'en']setFallback() changes the chain later and getFallback() returns its first entry.
has(key) and hasForLocale(key, locale) report whether a line exists in one specific locale. They do not consult the fallback chain, so has('greeting') is false for the French translator above even though get('greeting') finds the English line.
Pluralization
Plurals are written in one line, with the forms separated by a pipe, and chosen with choice(key, count). The count is added to the replacements automatically as :count (and {count}).
translator.addLines('en', {
apples: 'There is one apple|There are many apples',
items: ':count item|:count items',
})
translator.choice('apples', 1) // => 'There is one apple'
translator.choice('apples', 5) // => 'There are many apples'
translator.choice('items', 3) // => '3 items'Other replacements go in the third argument: translator.choice('items', 3, { shop: 'Acme' }).
Ranges
For counts that need their own wording, prefix a segment with an exact number in braces or an inclusive range in brackets. * means "and above". A matching range always wins over the position-based forms.
translator.addLines('en', {
notifications: '{0} No notifications|[1,19] :count notifications|[20,*] Lots of notifications',
})
translator.choice('notifications', 0) // => 'No notifications'
translator.choice('notifications', 5) // => '5 notifications'
translator.choice('notifications', 50) // => 'Lots of notifications'Languages With More Than Two Forms
Without ranges, the segment is chosen by the plural rule of the locale, and each language declares how many forms it has. English, German and Spanish have two (one, other). French treats 0 and 1 as the singular. Russian, Ukrainian, Polish, Czech and other Slavic languages have three forms, Arabic has six, and Japanese, Chinese and Korean have one. Regional variants such as pt_BR and zh-TW use the rule of their base language. A locale with no known rule always uses the first segment.
Write the forms in the order the language expects:
const ru = new Translator({ locale: 'ru', fallback: 'ru' })
ru.addLines('ru', { apples: ':count яблоко|:count яблока|:count яблок' })
ru.choice('apples', 1) // => '1 яблоко'
ru.choice('apples', 2) // => '2 яблока'
ru.choice('apples', 5) // => '5 яблок'
ru.choice('apples', 21) // => '21 яблоко'
ru.choice('apples', 11) // => '11 яблок'getPluralIndex(locale, count) returns the index of the segment the rule picks, if you need it directly:
import { getPluralIndex } from '@plinthjs/localization'
getPluralIndex('fr', 0) // => 0
getPluralIndex('en', 0) // => 1
getPluralIndex('ar', 11) // => 4Range and {n} segments never consume a position. In '{0} none|one|few|many' the plain forms are numbered from zero among themselves, so Russian 1, 3 and 5 pick one, few and many while 0 picks the explicit {0} form. This works for any language, including Arabic's six forms.
Loading Messages From Files
Registering everything in code gets unwieldy. A Translator can load from a directory instead, reading files only when a lookup needs them and caching the result. Files are plain JSON, read synchronously.
lang/
en/
auth.json
fr/
auth.json
fr.jsonlang/en/auth.json and lang/fr/auth.json are grouped files: the file name is the first segment of the key.
{
"failed": "These credentials do not match our records.",
"throttle": "Too many attempts. Try again in :seconds seconds."
}lang/fr.json is a JSON-strings file: a flat map keyed by source sentence.
{
"I love programming.": "J'adore programmer.",
"Welcome, :name": "Bienvenue, :name"
}Point the translator at the directory with addPath:
const t = new Translator({ locale: 'fr', fallback: 'en' }).addPath('lang')
t.get('auth.failed') // reads lang/fr/auth.json => 'Ces identifiants ne correspondent pas.'
t.get('auth.throttle', { seconds: 5 }) // not in fr, falls back to lang/en/auth.json
t.get('I love programming.') // => "J'adore programmer."
t.get('Welcome, :name', { name: 'Ada' }) // => 'Bienvenue, Ada'
t.get('Unknown sentence.') // => 'Unknown sentence.'Files are resolved relative to the working directory when the path is relative; pass an absolute path to be independent of where the process starts. A file that does not exist is simply a miss, never an error.
Lines you add in code with addMessages, addLines or addStrings and lines from files live side by side, and a flat JSON string wins over a grouped key with the same text.
Namespaces
A package or module can ship its own translations under a namespace, so its keys never collide with yours. Register the directory with addNamespace and address lines as namespace::group.key.
t.addNamespace('billing', 'node_modules/billing/lang')
t.get('billing::messages.title') // reads node_modules/billing/lang/<locale>/messages.jsonMore JSON Directories
addJsonPath(directory) registers an additional directory of <locale>.json files. Directories are merged in the order added, and later ones override earlier ones for the same sentence. This is how a package can contribute sentences on top of the application's own.
Custom Loaders
Under the hood, addPath, addNamespace and addJsonPath create a FileLoader. If your messages come from somewhere else, implement the Loader interface (a single load(locale, group, namespace?) method that returns a bag or undefined) and install it with setLoader. A loader's load is synchronous. The reserved group '*' (exported as JSON_GROUP) asks for the flat JSON-strings bag of a locale.
import { FileLoader, Translator } from '@plinthjs/localization'
import type { Loader } from '@plinthjs/localization'
const loader: Loader = {
load(locale, group) {
return cache.get(`${locale}/${group}`) // a nested bag, or undefined
},
}
const t = new Translator({ locale: 'en', fallback: 'en' }).setLoader(loader)
t.getLoader() === loader // => true
new FileLoader({ directory: 'lang' }) // a loader you can also build and install yourselfOnce a custom loader is installed, addPath, addNamespace and addJsonPath throw, because only a FileLoader can be configured that way.
Helper Functions
For code that just wants to translate a string, createTranslationHelpers returns plain functions bound to one translator: __, trans (the same function) and trans_choice.
import { createTranslationHelpers } from '@plinthjs/localization'
const { __, trans_choice } = createTranslationHelpers(translator)
__('welcome', { name: 'ada' }) // => 'Welcome, Ada!'
__('auth.failed', {}, 'es') // a specific locale
trans_choice('apples', 2) // => 'There are many apples'The helpers do not capture any locale. They always read the translator's current state, so a later setLocale or addMessages is seen by every helper you already handed out.
Using Translations in Views
Share the helpers with your templates to translate inside a view:
import { ViewEngine } from '@plinthjs/view'
const helpers = createTranslationHelpers(translator)
const views = new ViewEngine()
views.share(helpers)
views.register('greeting', '<h1>{{ __("welcome", { name: user.name }) }}</h1>')
views.render('greeting', { user: { name: 'ada' } }) // => '<h1>Welcome, Ada!</h1>'__, trans and trans_choice are all callable from a template once shared. (Other identifiers that begin with two underscores stay reserved for the engine's own runtime.)
If the locale changes per request, share a function created for that request, or call setLocale before rendering.
Translating Validation Messages
The validator takes plain message overrides, so you can build them from your translator:
const messages = {
required: translator.get('validation.required'),
'email.email': translator.get('validation.email'),
}
Validator.make(data, rules, messages)The validator's attributes map (the fourth argument to Validator.make, or setAttributeNames()) translates field names shown as :attribute: { email: translator.get('fields.email') }.
Testing
A translator needs no setup beyond new Translator(...) and in-memory lines, so tests can build one, add the lines they care about, and assert on get and choice. Switch locales with setLocale to test each language.