108 lines
1.7 KiB
Markdown
108 lines
1.7 KiB
Markdown
---
|
|
order: 4
|
|
---
|
|
|
|
# Internationalization
|
|
|
|
NocoBase uses i18next for internationalization support, unified front and back end, namespace support, perfect for NocoBase plugin system.
|
|
|
|
## Server side
|
|
|
|
Initialize i18n
|
|
|
|
```ts
|
|
const app = new Application({
|
|
i18n: {},
|
|
});
|
|
|
|
// Translate
|
|
app.i18n.t('hello');
|
|
```
|
|
|
|
In middleware using
|
|
|
|
```ts
|
|
async (ctx, next) => {
|
|
ctx.body = ctx.t('hello');
|
|
// In middleware i18n is cloneInstance
|
|
ctx.i18n.changeLanguage('zh-CN')
|
|
}
|
|
```
|
|
|
|
How to use the
|
|
|
|
```ts
|
|
// Add the plugin's language resources
|
|
app.i18n.addResources('zh-CN', 'nocobase-plugin-xxx', {
|
|
hello: 'hello plugin-xxx',
|
|
});
|
|
|
|
// need to specify ns, e.g.
|
|
app.i18n.t('hello', { ns: 'nocobase-plugin-xxx' });
|
|
|
|
// middleware
|
|
async (ctx, next) => {
|
|
ctx.body = ctx.t('hello', { ns: 'nocobase-plugin-xxx' });
|
|
}
|
|
```
|
|
|
|
## Client
|
|
|
|
To use in a component, by way of the `useTranslation` hook.
|
|
|
|
```js
|
|
import { useTranslation } from 'react-i18next';
|
|
|
|
export default () => {
|
|
const { t, i18n } = useTranslation('nocobase-plugin-xxx');
|
|
|
|
return (
|
|
<div>
|
|
<button
|
|
onClick={() => {
|
|
i18n.changeLanguage('en');
|
|
}}
|
|
>
|
|
en
|
|
</button>
|
|
<button
|
|
onClick={() => {
|
|
i18n.changeLanguage('cn');
|
|
}}
|
|
>
|
|
cn
|
|
</button>
|
|
<p>{t('hello')}</p>
|
|
</div
|
|
);
|
|
};
|
|
```
|
|
|
|
Used in Schema to inject t into scope
|
|
|
|
```js
|
|
import { i18n, createSchemaComponent } from '@nocobase/client';
|
|
|
|
const SchemaComponent = createSchemaComponent({
|
|
scope: {
|
|
t: i18n.t,
|
|
}
|
|
});
|
|
|
|
const schema = {
|
|
type: 'void',
|
|
title: "{{ t('hello') }}",
|
|
'x-component': 'Hello',
|
|
};
|
|
|
|
export default () => {
|
|
return (
|
|
<SchemaComponent schema={schema}/>
|
|
);
|
|
}
|
|
```
|
|
|
|
## Example
|
|
|
|
[click here for the full example](#)
|