Skip to content

Usage in JavaScript files

Francesco Novy edited this page Nov 20, 2018 · 1 revision

The provided l10n helper can be used to translate strings in your JavaScript files:

export default Component.extend({
  l10n: service()
});

Singular translations:

The t method provides gettext singularization for message ids. Placeholders can be provided as a hash, as the second argument.

l10n.t('Your current role: {{role}}', { role: 'Administrator' });

If you have strings which are variables (e.g. enums), you can also use the tVar method: l10n.tVar(myVariable). It works the same way as the t method, but it will be ignored by the gettext parser.

Plural translations:

The n method provides gettext pluralization for message ids. It takes singular and plural message ids as well as actual amount as arguments. All placeholders can be provided as a hash, as the last argument.

Short version:

l10n.n("{{count}} apple", "{{count}} apples", count);

With placeholders:

l10n.n( 
  "{{customCount}} apple from shop {{shopName}}", 
  "{{customCount}} apples from shop {{shopName}}", 
  countProperty, 
  { customCount: 5, shopName: 'My shop' }
);

Contextual translations:

To support contextual translations, there exist both pt and pn methods, which accept a context as 2nd or 4th parameter:

l10n.pt("user" "MY_CONTEXT");
l10n.pn("user", "users", countProperty, "MY_CONTEXT");

Please note: Both contextual methods also accept placeholders just as their non-contextual counterparts t and n.

A note on template literals

While you can use template literals for your translations, like this:

l10n.t(`This is a text

with new lines!`);

you may not use any template literal placeholders in there - e.g.

l10n.t(`this is ${myMood}!`)`. 

Instead, you have to use gettext placeholders:

l10n.t(`this is {{myMood}}`, { myMood });