多语言

amis 中对多语言的支持有两方面:

  1. amis 内部组件的多语言,比如日期组件中的日期
  2. JSON 配置中的多语言,比如配置中的 label 值

amis 内部组件多语言

分为 JS SDK 和 React 两种用法。

JS SDK

从 1.1.0 版本开始已经自带英文翻译,所以只需要在 props 里设置 locale 即可。

  1. let amisScoped = amis.embed(
  2. '#root',
  3. {
  4. type: 'page',
  5. title: '表单页面',
  6. body: {
  7. type: 'form',
  8. mode: 'horizontal',
  9. api: '/saveForm',
  10. body: [
  11. {
  12. label: 'Name',
  13. type: 'input-text',
  14. name: 'name'
  15. }
  16. ]
  17. }
  18. },
  19. {
  20. locale: 'en-US'
  21. }
  22. );

如果是其它语言,比如目前德语,需要单独引入文件

  1. <script src="sdk.js"></script>
  2. <script src="locale/de-DE.js"></script>
  3. <script type="text/javascript">
  4. (function () {
  5. let amis = amisRequire('amis/embed');
  6. // 通过替换下面这个配置来生成不同页面
  7. let amisJSON = {
  8. type: 'page',
  9. body: {
  10. type: 'form',
  11. mode: 'horizontal',
  12. api: '/saveForm',
  13. body: [
  14. {
  15. label: 'Name',
  16. type: 'input-text',
  17. name: 'name'
  18. },
  19. {
  20. label: 'Email',
  21. type: 'input-email',
  22. name: 'email'
  23. }
  24. ]
  25. }
  26. };
  27. let amisScoped = amis.embed('#root', amisJSON, {
  28. locale: 'de-DE'
  29. });
  30. })();
  31. </script>

React

React 版本中没有内置英文翻译,需要自己 import,使用如下方法:

  1. import 'amis-ui/lib/locale/en-US';

在渲染 amis 组件的时候设置 locale 为 en-US

  1. {
  2. renderAmis(
  3. {
  4. type: 'page',
  5. title: '简单页面',
  6. body: '内容'
  7. },
  8. {
  9. locale: 'en-US'
  10. }
  11. );
  12. }

全局文本替换

1.5.0 及以上版本

amis 渲染的 env 参数可以配置全局文本替换,能基于它实现多语言替换功能

  1. // sdk 中的写法
  2. let amisScoped = amis.embed(
  3. '#root',
  4. amisJSON,
  5. {
  6. // 这是 props
  7. },
  8. {
  9. replaceText: {
  10. AMIS_HOST: 'https://baidu.gitee.io/amis'
  11. }
  12. }
  13. );

比如下面的例子会对 AMIS_HOST 进行替换

```schema: scope=”body” { “type”: “tpl”, “tpl”: “AMIS_HOST” }

  1. 这个配置会对配置中的绝大部分字段进行替换,除了 `type, name, mode, target, reload` 这几个有特殊功能的字段。
  2. 可以通过配置 `replaceTextIgnoreKeys` 属性来进行修改,让其它字段也避免被替换。
  3. ## JSON 配置中设置多语言
  4. JSON 配置中,也可以设置不同语言下的不同展现,比如前面设置了 `locale` `en-US`,这时在任意 JSON 配置中都能使用 `en-US` 对象来覆盖这个语言下的效果,用于实现简单的替换效果。
  5. ```schema: scope="body"
  6. {
  7. "type": "form",
  8. "body": [{
  9. "type": "input-text",
  10. "name": "name",
  11. "label": "姓名:",
  12. "en-US": {
  13. "label": "username: "
  14. }
  15. }]
  16. }

请点击上方的切换语言下拉框切换到英文,就能看到 label 属性被替换了,除了 label 以外,还可以覆盖其他任意属性,比如将 type 换成其他。

扩展内置组件的语言

如果想扩展其他语言,首先参考 https://github.com/baidu/amis/blob/master/src/locale/en-US.ts 文件,然后参考后面的示例注册新语言,未翻译的文字都将使用中文。

JS SDK 扩展方法

  1. let amisLib = amisRequire('amis');
  2. amisLib.registerLocale('jp', {
  3. 'Form.submit': '送信'
  4. });

React 扩展方法

  1. import {registerLocale} from 'amis';
  2. registerLocale('jp', {
  3. 'Form.submit': '送信'
  4. });