Skip to main content

Internationalization

Tymber provides a built-in internationalization (also known as "i18n") system that automatically loads translations from your module's assets.

File structure

Translations are stored in the assets/i18n directory of your module with a .json extension:

my-module/
├── assets/
│ ├── i18n/
│ ├── migrations/
│ ├── static/
│ └── templates/
├── src/
│ ├── admin-endpoints/
│ ├── admin-views/
│ ├── endpoints/
│ ├── repositories/
│ ├── services/
│ ├── utils/
│ └── views/
└── test/

Examples:

  • assets/i18n/en.json
  • assets/i18n/en-CA.json
  • assets/i18n/fr.json

File Format

The JSON files can contain nested objects. It can also contain templates:

assets/i18n/en.json
{
"welcome": "Welcome, <%= name %>!",
"auth": {
"login": "Login"
}
}
assets/i18n/fr.json
{
"welcome": "Bonjour, <%= name %> !",
"auth": {
"login": "Se connecter"
}
}

Usage

In templates

The framework automatically injects a $t() function into your view data.

<h1><%= $t('welcome', { name: 'John' }) %></h1>
<p><%= $t('auth.login') %></p>

In components

You can also use the I18nService directly:

import { I18nService, HttpContext, INJECT, Endpoint } from "@tymber/core";

export class MyEndpoint extends Endpoint {
static [INJECT] = [I18nService];

constructor(private readonly i18n: I18nService) {
super();
}

async handle(ctx: HttpContext) {
const message = this.i18n.translate(ctx, ctx.locale, "welcome", {
name: "John",
});
// ...
}
}

Locale Detection

Tymber automatically detects the user's preferred locale by parsing the Accept-Language header of the incoming request. The detected locale is available as ctx.locale.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept-Language