Created
February 28, 2025 22:09
-
-
Save migmolrod/f10eb6d1403f3c2075f96e9dee693078 to your computer and use it in GitHub Desktop.
ngx-translate/xliff-loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TranslateLoader } from '@ngx-translate/core'; | |
import { HttpClient } from '@angular/common/http'; | |
import { Injectable } from '@angular/core'; | |
import { Observable, of } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
import { XMLParser } from 'fast-xml-parser'; | |
type TransUnit = { | |
id: string; | |
segment: { | |
source: { '#text': string; 'xml:lang': string }; | |
target: { '#text': string; 'xml:lang': string }; | |
}; | |
}; | |
type Translation = { [key: string]: string }; | |
@Injectable() | |
export class XliffLoader implements TranslateLoader { | |
private parser = new XMLParser({ | |
ignoreAttributes: false, | |
attributeNamePrefix: '', | |
}); | |
constructor(private http: HttpClient) {} | |
getTranslation(lang: string): Observable<Translation> { | |
if (lang === 'en') { | |
return of({}); | |
} | |
return this.http | |
.get(`/i18n/messages.${lang}.xlf`, { responseType: 'text' }) | |
.pipe(map((xml: string) => this.parseXliff(xml))); | |
} | |
private parseXliff(xml: string): Translation { | |
const parsed = this.parser.parse(xml); | |
const translations: Translation = {}; | |
const transUnits = parsed.xliff.file.body['unit']; | |
transUnits.forEach((unit: TransUnit) => { | |
const source = unit.segment.source; | |
const target = unit.segment.target; | |
// Fallback to source if target is missing | |
translations[source['#text']] = target['#text'] || source['#text']; | |
}); | |
return translations; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment