Internationalization¶
I18nService & I18nPipe¶
HortiView doesn't support adding separate module builds for multiple languages. Instead, the language is being passed to the module in the runtime with the rest of the custom props in the mount
function (in loadApp.ts
). To facilitate translating strings in the runtime there are I18nService
and I18nPipe
(you can absolutely do it your own way, too). I18nService.setLocale
is called in the constructor of AppComponent
to set the currently used locale file from assets/locale
@Injectable({
providedIn: 'root'
})
export class I18nService {
private dictionary: { [p: string]: string } = {};
///.
public setLocale(locale: Locale) {
import(`../assets/locale/${ locale }.json`).then(x =>
this.dictionary = x.default);
}
}
The locale files are just simple jsons
{
"first works!": "¡primeros trabajos!",
"second works!": "¡segundos trabajos!",
"home works!": "¡trabajos en casa!",
"Take me to first": "Llévame al primero",
"Take me to second": "Llévame al segundo",
"Take me to home": "Llévame a casa"
}
In order to translate strings in typescript code you use the translate$
observable from I18nService
:
and to translate strings in the template files you can use the i18n pipe:
The pipe uses the translate$
observable from I18nService
which will try to get the translation for the given key, and if it fails to do so, will return the key. If there are not values for the given key, there will be a warning printed to the console.