Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save michaelbromley/a2278db0748ad22f4d68fc58aa44ab67 to your computer and use it in GitHub Desktop.
Save michaelbromley/a2278db0748ad22f4d68fc58aa44ab67 to your computer and use it in GitHub Desktop.
Experimental co-located localization tokens
// This is a build step which would be run whenever component messages are modified.
// It scans the project for co-located *.messages.json files, extracts the tokens
// and prepends them with the components' selector as a scoping mechanism.
// pseudo-code
var componentMessages = getComponentMessageFiles("**/*.messages.json");
var componentTokens = {};
foreach (messageFile in componentMessages) {
var componentSelector = getComponentSelector(messageFile.path);
var scopedTokens = createScopedTokens(componentSelector, messageFile.text);
componentTokens = merge(componentTokens, scopedTokens);
}
writeFile(componentTokens, './component.messages.json;);
import { ChangeDetectorRef, ElementRef, Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
/**
* An experimental pipe for translating co-located translation tokens in Angular.
*/
@Pipe({
name: 'i18n',
})
export class I18nPipe implements PipeTransform {
private translatePipe: TranslatePipe;
constructor(private translateService: TranslateService, private changeDetector: ChangeDetectorRef, private elementRef: ElementRef) {
// Instantiate the ngx-translate TranslatePipe which we will delegate the actual translation to.
this.translatePipe = new TranslatePipe(translateService, changeDetector);
}
transform(value: any, ...args: any[]): any {
// Construct a translation token based on the component's tagName
// combined with the token as specified in the template.
// E.g. when the token "TRANSLATE_ME" is used in the component <my-component>, the token
// passed to the TranslatePipe will be "MY-COMPONENT:TRANSLATE_ME"
const componentTagName = this.elementRef.nativeElement.tagName;
const token = `${componentTagName}:${value}`;
return this.translatePipe.transform(token, ...args);
}
}
<h1>{{ 'TRANSLATE_ME' | i18n }}</h1>
{
"TRANSLATE_ME": {
"en": "Translate me",
"de": "Übersetze mich"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment