tachybase_todo/docs/guide/plugin-development/i18n.md

108 lines
1.7 KiB
Markdown
Raw Normal View History

---
order: 4
---
# Internationalization
2021-10-31 09:44:52 +08:00
NocoBase uses i18next for internationalization support, unified front and back end, namespace support, perfect for NocoBase plugin system.
2021-10-31 09:44:52 +08:00
## Server side
2021-10-31 09:44:52 +08:00
Initialize i18n
```ts
const app = new Application({
i18n: {},
});
2021-10-31 09:44:52 +08:00
// Translate
app.i18n.t('hello');
```
2021-10-31 09:44:52 +08:00
In middleware using
```ts
async (ctx, next) => {
ctx.body = ctx.t('hello');
2021-10-31 09:44:52 +08:00
// In middleware i18n is cloneInstance
ctx.i18n.changeLanguage('zh-CN')
}
```
2021-10-31 09:44:52 +08:00
How to use the
```ts
2021-10-31 09:44:52 +08:00
// Add the plugin's language resources
app.i18n.addResources('zh-CN', 'nocobase-plugin-xxx', {
2021-10-31 09:44:52 +08:00
hello: 'hello plugin-xxx',
});
2021-10-31 09:44:52 +08:00
// need to specify ns, e.g.
app.i18n.t('hello', { ns: 'nocobase-plugin-xxx' });
2021-10-31 09:44:52 +08:00
// middleware
async (ctx, next) => {
ctx.body = ctx.t('hello', { ns: 'nocobase-plugin-xxx' });
}
```
2021-10-31 09:44:52 +08:00
## Client
2021-10-31 09:44:52 +08:00
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>
2021-10-31 09:44:52 +08:00
</div
);
};
```
2021-10-31 09:44:52 +08:00
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}/>
);
}
```
2021-10-31 09:44:52 +08:00
## Example
2021-10-31 09:44:52 +08:00
[click here for the full example](#)