1.7 KiB
1.7 KiB
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
const app = new Application({
i18n: {},
});
// Translate
app.i18n.t('hello');
In middleware using
async (ctx, next) => {
ctx.body = ctx.t('hello');
// In middleware i18n is cloneInstance
ctx.i18n.changeLanguage('zh-CN')
}
How to use the
// 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.
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
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}/>
);
}