Trails Internationalization (I18n) API
See also: Guides index · Trails Idioms · i18n package · activesupport package · Configuring Trails Applications
@blazetrails/i18n is the port of the Ruby i18n gem, and Trails wires it up the way Rails does. After reading this guide you will know:
- How the I18n API is split between a front end and a backend.
- How to pick a locale for each request.
- How to put translations in your views, models and mailers, and how keys are looked up.
- How interpolation, pluralization and date formats work.
- How to swap the backend or the handler for missing translations.
How I18n in Trails Works
Internationalizing an application means two jobs: pulling every user-facing string and format out of the code (internationalization), and supplying those strings and formats for each language you support (localization). Trails gives you the first; you write the second as locale files.
The Overall Architecture of the Library
The library has two halves. The public API is a set of functions — translate, localize, setLocale and friends — that your code calls. Behind them sits a backend that stores the translation data and answers lookups. The default backend is Simple, an in-memory store loaded from files; you can replace it with any object that answers the same methods.
The Public I18n API
The functions you will use most are translate (aliased t) and localize (aliased l). The rest read or change configuration:
import {
availableLocales,
defaultLocale,
locale,
localize,
setLocale,
translate,
} from "@blazetrails/i18n";
translate("store.title");
localize(new Date());
locale(); // the current locale
setLocale("de");
defaultLocale(); // used when no locale is set
availableLocales(); // every locale the backend has data forEach Ruby I18n.locale = ... writer is a setX function here, because a module-level binding cannot be assigned from outside its module. Loading files is asynchronous (setLoadPath, reloadBang), while every lookup stays synchronous; why the split falls there is ruled in the i18n package notes.
Setup the Trails Application for Internationalization
Configure the I18n Module
An application keeps its translations under config/locales/, and every file there is added to the load path at boot. The config.i18n settings in config/application.ts pick the default and the allowed locales:
import { Application } from "@blazetrails/trailties";
export class Blog extends Application {
static {
this.config.i18n.defaultLocale = "en";
this.config.i18n.availableLocales = ["en", "de", "pt-BR"];
this.config.i18n.loadPath.push("config/locales/**/*.yml");
}
}A locale file is YAML keyed by locale first:
en:
hello: "Hello world"
de:
hello: "Hallo Welt"A locale can also be a TypeScript module exporting the same tree. Importing a module is asynchronous, so it is registered with registerLocaleModule before its path joins the load path.
Managing the Locale across Requests
The locale is per request: a visitor who asked for German should not leave German behind for the next one. Set it in an aroundAction with withLocale, which restores the previous value when the block returns:
import { ActionController } from "@blazetrails/actionpack";
import { defaultLocale, withLocale } from "@blazetrails/i18n";
class ApplicationController extends ActionController.Base {
static {
this.aroundAction(":switchLocale");
}
async switchLocale(action: () => Promise<unknown>): Promise<void> {
const requested = this.params.fetch("locale", null) as string | null;
await withLocale(requested ?? defaultLocale(), action);
}
}Where the locale comes from is your choice. The common sources are:
- A URL parameter or path segment (
/de/articles). Declare a(:locale)scope in the routes and return{ locale: ... }fromdefaultUrlOptionsso every generated link carries it. - The domain (
example.de) or a subdomain (de.example.com), read offthis.request. - The
Accept-Languageheader, or a preference stored on the signed-in user.
Whatever the source, check it against availableLocales() before using it. With enforceAvailableLocales on (the default), passing an unknown locale raises InvalidLocale (exported from @blazetrails/i18n).
Internationalization and Localization
Abstracting Localized Code
Replace each literal string in a view or controller with a key:
<h1><%= t("hello") %></h1>and read a key from a controller the same way:
import { ActionController } from "@blazetrails/actionpack";
import { t } from "@blazetrails/i18n";
class HomeController extends ActionController.Base {
index() {
return this.render({ plain: String(t("hello")) });
}
}Providing Translations for Internationalized Strings
Each key then needs a value in each locale file. A key missing from a locale renders as a translation missing span in a view, so the gap is visible rather than blank.
Passing Variables to Translations
A value can name placeholders with %{name}, filled from the options:
import { translate } from "@blazetrails/i18n";
// en: greeting: "Hello, %{name}!"
translate("greeting", { name: "Ada" }); // "Hello, Ada!"A placeholder with no matching option raises MissingInterpolationArgument (exported from @blazetrails/i18n). Keys such as scope, default, count and locale are reserved and cannot be placeholders.
Adding Date/Time Formats
localize formats a date or time with the date.formats / time.formats entries of the locale. Pass format to pick one by name; a name is written with its leading colon, which is how trails keeps Ruby's Symbol-or-String distinction (see CLAUDE.md, "A Ruby Symbol is a JS string"):
import { localize } from "@blazetrails/i18n";
// en: time: formats: short: "%H:%M"
localize(new Date(), { format: ":short" });Inflection Rules for Other Locales
ActiveSupport::Inflector takes per-locale rules, so pluralize and singularize can follow a language other than English. See the activesupport package.
Localized Views
A template can be localized as a whole: with the locale set to de, index.de.html.tse is picked before index.html.tse. This suits long, mostly static pages better than one key per sentence.
Organization of Locale Files
One file per locale soon grows unwieldy. Every file under config/locales/ is loaded, so you can split by area — models/article/de.yml, views/articles/de.yml — and add the nested directories to loadPath with a glob, as above.
Overview of the I18n API Features
Looking up Translations
A key is a dot-separated path into the tree. scope prefixes it, and an array of keys returns an array of values:
import { translate } from "@blazetrails/i18n";
translate("activerecord.errors.messages.blank");
translate("blank", { scope: "activerecord.errors.messages" });
translate("blank", { scope: ["activerecord", "errors", "messages"] });
translate(["odd", "even"], { scope: "activerecord.errors.messages" });default supplies a fallback. A string is used as it is; a string with a leading colon is another key to try, and an array lists several in order:
import { translate } from "@blazetrails/i18n";
translate("missing", { default: "Not here" });
translate("missing", { default: [":also_missing", "Not here"] });Asking for an inner node returns the whole subtree as an object.
Lazy Lookup
Inside a view, a key that starts with a dot is relative to the template's path. In app/views/books/index.html.tse, t(".title") looks up books.index.title. In a controller the prefix is the controller path plus the action name.
Pluralization
The count option both interpolates %{count} and picks a plural form. The default rule is English's: one for 1, other for everything else, and zero when that key exists:
import { translate } from "@blazetrails/i18n";
// en: inbox: { one: "1 message", other: "%{count} messages" }
translate("inbox", { count: 2 }); // "2 messages"Languages with other rules plug them in through the Pluralization backend module.
Setting and Passing a Locale
Any lookup can name its locale directly, without touching the current one:
import { localize, translate } from "@blazetrails/i18n";
translate("hello", { locale: "de" });
localize(new Date(), { locale: "de" });Using Safe HTML Translations
A key whose name ends in _html, or whose last segment is html, is marked HTML-safe by the view helper t, so its markup is not escaped. Interpolated values are still escaped.
Translations for Active Record Models
Model.modelName.human() and Model.humanAttributeName("title") read their names from activerecord.models and activerecord.attributes. Validation messages are looked up from the most specific key to the most general: activerecord.errors.models.article.attributes.title.blank, then the model, then activerecord.errors.messages.blank, then errors.messages.blank. A message can interpolate %{model}, %{attribute}, %{value} and %{count}.
Translations for Action Mailer E-Mail Subjects
A mailer action that does not pass a subject to mail looks one up at <mailer_scope>.<action_name>.subject. See Action Mailer Basics.
Overview of Other Built-In Methods that Provide I18n Support
The framework reads its own strings through I18n as well: Action View's date and number helpers (distanceOfTimeInWords, numberToCurrency, dateSelect), Active Model's error messages and human names, and Active Support's toSentence and ordinalize. Each ships English defaults you can override in your locale files.
How to Store your Custom Translations
The Simple backend reads YAML and TypeScript locale files. You can also put data in directly, which tests often do:
import { backend, translate } from "@blazetrails/i18n";
backend().storeTranslations("en", { greeting: "Hello, %{name}!" });
translate("greeting", { name: "Ada" });Customize your I18n Setup
Using Different Backends
setBackend replaces the store. The package ships KeyValue (for an external store), Chain (try several backends in order) and modules such as Fallbacks and Pluralization that add behaviour to a backend. See the i18n package.
Using Different Exception Handlers
When a lookup misses, the configured exception handler decides what happens. The default returns a "translation missing" message; setExceptionHandler installs your own, and translateBang (t! in Ruby) raises MissingTranslationData (exported from @blazetrails/i18n) instead. In tests, config.i18n.raiseOnMissingTranslations turns every miss in a view or controller into a raise.