Auto-generating keys
By default, ember-intl asks you to come up with translation keys in /translations.
import { t } from 'ember-intl';
<template>
{{t "hello.message" name="Zoey"}}
</template>2
3
4
5
{
"hello.message": "Hello, {name}!"
}2
3
Manually creating and maintaining keys can be cumbersome if you have a production app and need to support many locales.
Here's how you can auto-generate keys.
1. Use formatMessage
In templates, use the formatMessage helper and pass the translation that you want for your default locale.
import { formatMessage } from 'ember-intl';
<template>
{{formatMessage "Hello, {name}!" name="Zoey"}}
</template>2
3
4
5
In classes, you have the option to inject the intl service.
import { type Registry as Services, service } from '@ember/service';
import Component from '@glimmer/component';
import { t } from 'ember-intl';
interface HelloSignature {
Args: {
name: string;
};
}
export default class Hello extends Component<HelloSignature> {
get message(): string {
const { name } = this.args;
return this.intl.formatMessage('Hello, {name}!', {
name,
});
}
<template>
{{this.message}}
</template>
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2. Extract translations
Install @formatjs/cli as a development dependency, then add the following script:
{
"scripts": {
"extract-translations": "formatjs extract \"app/**/*.{gjs,gts,hbs,js,ts}\" --format simple --ignore \"**/*.d.ts\" > translations/en-us.json"
},
"devDependencies": {
"@formatjs/cli": "..."
}
}2
3
4
5
6
7
8
Run the script to get the translation file for the default locale.
{
"tBFOH1": "Hello, {name}!"
}2
3
Now that you have a translation file with unique keys, you can create translation files for the other locales in one of two ways:
- Manual: Duplicate the default locale file, then update translations.
- Use a Translation Management System (TMS).
3. Convert formatMessage to t
Lastly, we need to change all the formatMessage's to t's, so that your users see the right translations when the locale is changed. You can install ember-formatjs to transform code at build time.
import { t } from 'ember-intl';
<template>
{{t "tBFOH1" name="Zoey"}}
</template>2
3
4
5