Use translations stored in Sitecore items
The SPEAK 3 translation mechanism uses the Angular ngx-translate service. You can define translations in Sitecore items, and configure ngx-translate to retrieve and use these translations. You use the SciTranslateLoader
service for this
This topic describes how to:
Specify translations in a Sitecore instance
To specify translations in a Sitecore instance:
-
Use the Speak3DictionaryFolder template to create an item called Translations as a child of your application item. The name, Translations, is only a convention, but you cannot use Dictionary (that name is reserved).
-
Add an item based on the Speak3DictionaryEntry template for each translation you need. Add all these items as immediate children of the Translations item. We recommended that you enter a value in all upper case in the Key field of these items.
-
Note the item ID of the Translations folder. You need this for the configuration later.
With this approach, you can use the service and pipes of ngx-translate
as usual because the NgScModule
exports these features.
This example shows the basic usage:
import { Component } from '@angular/core';
import { NgScService } from '@speak/ng-sc';
@Component({
selector: 'app-translate-demo',
template: `
<h1>Translate demo</h1>
<button [disabled]="locale === 'en'" (click)="switchLocale('en')">EN</button>
<button [disabled]="locale === 'da'" (click)="switchLocale('da')">DK</button>
<button [disabled]="locale === 'ca-ES'" (click)="switchLocale('ca-ES')">CAT</button>
<div>Fish: <span>{{ 'FISH' | translate }}</span></div>
<div>Pork: <span>{{ 'PORK' | translate }}</span></div>
<div>Vegetables: <span>{{ 'VEGETABLE' | translate }}</span></div>
`
})
export class TranslateDemoComponent {
// The currently active language.
locale = 'en';
constructor(
private ngScService: NgScService
) {}
// This method will switch the active language.
switchLocale(lang) {
this.locale = lang;
this.ngScService.switchLanguage(lang);
}
}
Configure the TranslateModule module individually
To configure the TranslateModule module individually, if you decide not to use the NgScModule
:
-
In
app.module.ts
:RequestResponseshellimport { HttpModule, Http } from '@angular/http'; import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { SciTranslateLoader, TRANSLATE_ITEM_ID } from '@speak/ng-sc/ngx-translate-loader'; // other imports here @NgModule({ imports: [ // other imported modules here HttpModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useClass: SciTranslateLoader, deps: [Http, TRANSLATE_ITEM_ID] } }) ], providers: [ { provide: TRANSLATE_ITEM_ID, useValue: '99228409-8417-4692-A5B9-E59CC8AC74B9' } ] }) export class AppModule { }
You can use ngx-translate
to provide translations in your Angular app. There is more information in the official ngx-translate documentation.