Internationalization
Using Gem's i18n module, you can quickly add multi-language support to your application.
Getting started
import { I18n } from '@mantou/gem/helper/i18n';
const en = {
title: 'This is I18n',
};
const i18n = new I18n({
fallbackLanguage: 'en',
resources: {
en,
zh: () => import('./locales/zh.json'),
},
});
console.log(i18n.get('title'));When instantiating the I18n object, the appropriate language is automatically selected according to the browser settings. A language pack can be an object or a loader function for on-demand loading.
TIP
It is recommended to use Crowdin, Pontoon similar services to maintain your language pack
You can directly use i18n.get('title') in the element to read the value in the language pack.
@customElement('app-root')
class App extends GemElement {
@template()
#content = () => {
return html`
<button @click=${() => i18n.setLanguage('zh')}>zh</button>
<p>${i18n.get('title')}</p>
`;
};
}On-demand loading
A language pack can be a loader function. With dynamic imports in your bundler, each language is bundled into its own file and only the languages in use are loaded:
const i18n = new I18n({
fallbackLanguage: 'en',
resources: {
en: () => import('./locales/en.json'),
zh: () => import('./locales/zh.json'),
},
});A loader can return the language pack itself or a module whose default export is the language pack. The argument type of get is inferred from the loaded pack. For language packs outside the bundle, request them in the loader, e.g. () => fetch('/locales/zh.json').then((res) => res.json()).
Entries missing from the current language pack use the value from the fallback language (fallbackLanguage). The fallback pack is only loaded when a missing entry is read, and elements update automatically once it has loaded.
Loader functions are asynchronous: until the pack has loaded, get returns the value from the fallback language, or [key] if the fallback pack has not loaded either. For pure client-side rendering, wait for i18n.ready before the first render to avoid showing placeholders and then switching. With cache enabled, cached packs do not need to wait for loading:
await i18n.ready;
render(html`<app-root></app-root>`, document.body);Languages that must be available synchronously (e.g. the default language) can import the pack object directly, so only other languages are loaded on demand. With server-side rendering the client uses the packs output by the server and does not need to wait, see Server-side rendering.
Cache
Use cache to cache the language selected by the user, which is used directly the next time the user enters the App. The cached data will be saved to localStorage. With 'manual', call setCache to cache. Set cachePrefix when using I18n in a library to avoid conflicting with the application's cache.
With cache enabled, language packs loaded by loader functions are cached too. The next time the language is used, the cached pack is used synchronously while the loader runs; once it has loaded, the cache is updated and elements update automatically if the content changed. Each module only keeps the cache of the languages in use and the fallback language. Sub modules use the main module's cache setting and cache language packs only, not the language.
const i18n = new I18n({
cache: true,
fallbackLanguage: 'en',
resources: {
en,
zh: () => import('./locales/zh.json'),
},
});Variable substitution
In multilingual projects, variables are often embedded, such as:
html`Hello, ${username}`;When using Gem, you can use $ to mark variables, for example:
const i18n = new I18n({
fallbackLanguage: 'en',
resources: {
en: {
hello: 'Hello, $1! $2=> $1, Hello!',
},
},
});
html`${i18n.get('hello', 'World', 'reverse')}`;
// Hello, World! reverse=> World, Hello!The variable can also be a custom rendering function, which can customize the rendering of the content provided in the language template. The following example is to render the word detail specified in the language entry into a link:
const i18n = new I18n({
fallbackLanguage: 'en',
resources: {
en: {
detail: 'See $1<detail>, $1<detail2>',
},
},
});
html`${i18n.get('detail', (s) => html`<a href="#">${s}</a>`)}`;Language specified in URL
Some multi-language front-end projects may need SEO support, so you need to specify different language versions in the URL. urlParamsType allows I18n to check the URL when instantiating, and supports multiple types:
path: root path, for example/zh/homequerystring: located in URL query string, the name is specified withurlParamsNameccTLD: Country code top-level domain, such aswebsite.jpgTLD: Subdomain of a generic top-level domain, such asjp.website.com
const i18n = new I18n({
fallbackLanguage: 'en',
urlParamsType: 'ccTLD',
resources: {
en: {
title: 'This is I18n',
},
},
});TIP
When
urlParamsTypeispath, then the links in the page and therouting switch need to be modified, this operation can be defined globally by setting historyhistory.basePath:js new I18n({ urlParamsType: 'path', fallbackLanguage: 'zh-CN', resources: { 'zh-CN': zhCN, }, onChange(lang) { if (!history.basePath) { history.basePath = '/' + lang; const { path, query, hash } = history.getParams(); history.replace({ path, query, hash }); } else { const { path, query, hash } = history.getParams(); history.basePath = '/' + lang; history.replace({ path, query, hash }); } }, });
Sub module
I18n.createSubModule creates sub-modules, you can split language packages by route to speed up the rendering of the first screen. A sub module follows the main module when the language changes and uses its fallback language and cache settings, but does not modify the document's lang attribute, and only caches language packs, not the language:
// In the module of a route
const pageI18n = i18n.createSubModule('page', {
en: () => import('./locales/page/en.json'),
zh: () => import('./locales/page/zh.json'),
});
html`${pageI18n.get('title')}`;A sub module starts loading the pack of the current language when it is created, and get returns [key] until it has loaded. i18n.ready resolves when the main module and all sub modules have finished switching language; wait for it before rendering a freshly loaded module to avoid flickering:
const { default: Page } = await import('./page');
await i18n.ready;setLanguage on the main module also waits for all sub modules to finish switching.
Server-side rendering
When rendering with @mantou/gem-ssr, each request has its own language, set by calling setLanguage in the request. After rendering, every module whose get was called during the request outputs the pack of the current language (including values from the fallback language) to the page together with the stores. Unused modules and other languages are not output:
await runInRequest(async () => {
await i18n.setLanguage('zh');
return renderToString(html`<app-root></app-root>`);
});On the client, I18n and its sub modules use the packs output by the server directly without loading them again, so hydration matches the server content. The server needs to read fallback values synchronously, so it loads both the current language and the fallback language.
Localize
You can use <gem-route> to render different content according to different languages. You only need to specify the trigger to i18n:
const localizeRoutes = [
{
pattern: 'zh-*',
async getContent() {
import('...');
return html`other element`;
},
},
];
html`<gem-route .trigger=${i18n} .routes=${localizeRoutes}></gem-route>`;Example
import { render } from '@mantou/gem';
import { I18n } from '@mantou/gem/helper/i18n';
import type { RouteItem } from 'duoyun-ui/elements/route';
const en = {
title: 'This is I18n',
hello: 'Hello, $1! $2=> $1, Hello!',
detail: 'See $1<detail>, $1<detail2>',
};
const i18n = new I18n<typeof en>({
cache: true,
fallbackLanguage: 'en',
resources: {
en,
de: {
title: 'Das ist I18n',
},
// 按需加载,也可以是 `() => import('./zh.json')`
zh: async () => ({ title: '这是 I18n' }),
},
onChange: console.log,
});
const i18nModule = i18n.createSubModule<typeof en>('test', {
en,
de: {
title: 'Das ist I18n',
},
zh: async () => {
await new Promise((res) => setTimeout(res, 1000));
return { title: '这是 I18n' };
},
});
const localizeRoutes: RouteItem[] = [
{
pattern: 'en',
getContent() {
return html`en element`;
},
},
{
pattern: 'de',
getContent() {
return html`de element`;
},
},
{
pattern: '*',
getContent() {
return html`other element`;
},
},
];
@customElement('app-root')
export class App extends GemElement {
@template()
#render = () => {
return html`
<button @click=${() => i18n.setLanguage('de')}>de</button>
<button @click=${() => i18n.setLanguage('zh')}>zh</button>
<button @click=${() => i18n.setLanguage('en')}>en</button>
<button @click=${() => i18n.resetLanguage()}>reset</button>
<p>Current language: ${i18n.currentLanguage}</p>
<p>${i18n.get('title')}</p>
<p>${i18n.get('hello', 'World', 'reverse')}</p>
<p>${i18n.get('detail', (s) => html`<a href="#">${s}</a>`)}</p>
<h2>sub module</h2>
<p>${i18nModule.get('title')}</p>
<p>${i18nModule.get('hello', 'World', 'reverse')}</p>
<p>${i18nModule.get('detail', (s) => html`<a href="#">${s}</a>`)}</p>
<h2>localize content</h2>
<dy-route .trigger=${i18n} .routes=${localizeRoutes}></dy-route>
`;
};
}
render(
html`
<gem-examples-layout>
<app-root></app-root>
</gem-examples-layout>
`,
document.body,
);