Skip to main content

Using xliff

Install the xliff package:

npm i xliff
yarn add xliff

Replace the default http loader with the following loader implementation:

transloco-root.module.ts
import { HttpClient } from '@angular/common/http';
import {
TRANSLOCO_LOADER,
Translation,
TranslocoLoader,
TRANSLOCO_CONFIG,
translocoConfig,
TranslocoModule,
} from '@jsverse/transloco';
import { Injectable, isDevMode, NgModule } from '@angular/core';
import { from } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';
// xliff v1.2
import xliff from 'xliff/esm/xliff12ToJs';
// xliff v2
//import xliff from "xliff/esm/xliff2js";

function toTranslationFormat(json) {
const obj = json.resources.transloco;
return Object.keys(obj).reduce((acc, key) => {
acc[key] = obj[key].target;
return acc;
}, {});
}

@Injectable({ providedIn: 'root' })
export class TranslocoXliffHttpLoader implements TranslocoLoader {
constructor(private http: HttpClient) {}

getTranslation(lang: string) {
return this.http
.get<Translation>(`/assets/i18n/${lang}.xlf`, { responseType: 'text' })
.pipe(
switchMap((translation) => from(xliff(translation))),
map(toTranslationFormat),
);
}
}

@NgModule({
exports: [TranslocoModule],
providers: [
{
provide: TRANSLOCO_CONFIG,
useValue: translocoConfig({
availableLangs: ['en', 'es'],
defaultLang: 'en',
// Remove this option if your application
// doesn't support changing language in runtime.
reRenderOnLangChange: true,
prodMode: !isDevMode(),
}),
},
{ provide: TRANSLOCO_LOADER, useClass: TranslocoXliffHttpLoader },
],
})
export class TranslocoRootModule {}

The translation file (xliff v1.2):

<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="transloco">
<body>
<trans-unit id="title">
<source>Hello Transloco!</source>
<target>Bonjour Transloco!</target>
</trans-unit>
</body>
</file>
</xliff>