tachybase_todo/docs/guide/plugin-development/i18n.zh-CN.md
chenos ca7af9c8cc
feat: new version of the documentation (#95)
* feat: new version of the documentation

* feat: add English catalog translation

* Update quickstart.md

* Update quickstart.zh-CN.md

* Update quickstart.zh-CN.md

* Update quickstart.zh-CN.md

* Update quickstart.zh-CN.md

* feat: update quickstart

* update doc

* update pepository api doc

Co-authored-by: ChengLei Shao <chareice@live.com>
2021-10-28 22:55:51 +08:00

108 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
order: 4
---
# 国际化
NocoBase 使用 i18next 做国际化支持,前后端统一,支持 namespace非常适合 NocoBase 的插件系统。
## 服务端
初始化 i18n
```ts
const app = new Application({
i18n: {},
});
// 翻译
app.i18n.t('hello');
```
在中间件中使用
```ts
async (ctx, next) => {
ctx.body = ctx.t('hello');
// 在中间件中 i18n 是 cloneInstance
ctx.i18n.changeLanguage('zh-CN')
}
```
如何在插件中使用
```ts
// 添加插件的语言资源
app.i18n.addResources('zh-CN', 'nocobase-plugin-xxx', {
hello: '你好 plugin-xxx',
});
// 需要指定 ns
app.i18n.t('hello', { ns: 'nocobase-plugin-xxx' });
// 中间件
async (ctx, next) => {
ctx.body = ctx.t('hello', { ns: 'nocobase-plugin-xxx' });
}
```
## 客户端
在组件中使用,通过 `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>
);
};
```
在 Schema 中使用,将 t 注入给 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}/>
);
}
```
## 示例
[点此查看完整的示例](#)