国际化多语言

更新时间:2023-10-12 08:00:15下载pdf

控制面板的国际化多语言是开发过程中必不可少的一部分。tuya-panel-kit 中内置了 I18N 模块用于处理多语言需求。

定义多语言

请勿在本地代码内定义除中英文外的多语言。其他语种涉及多地区,本地代码无法全兼容,请在 涂鸦 IoT 平台产品多语言 页面设定 设备面板 的多语言配置。

src/i18n/strings.{js,ts} 文件中进行编辑。

// en 和 zh 必须都定义
export default {
  en: {
    hello: 'Hello',
  },
  zh: {
    hello: '你好',
  }
};

生成并导出多语言

src/i18n/index.{js,ts} 文件中进行实例化导出。

import { I18N } from 'tuya-panel-kit';
import Strings from './strings';

export default new I18N(Strings);

使用多语言

可在任意需要使用多语言的场景进行调用。

import Strings from '../i18n';

const localizedText = Strings.getLang('hello');

console.log(localizedText);

多语言 Key 命名规范

bitmap 类型使用详情参见 bitmap 型如何使用

export default {
  en: {
    dsc_edit: 'Edit', // Basic multi language with dsc_ start and name it semantically
    dsc_countdown_on: 'Turn on after {0}',
    dp_switch: 'Switch', // Datapoint (DP) related multi language should be in accordance with the `dp_${dpCode}`
    dp_switch_on: 'Switch is On', // Boolean type datapoint related multi language should be in accordance with the `dp_${dpCode}_${'on' || 'off'}`
    dp_mode_smart: 'Smart Mode', // Enum type datapoint related multi language should be in accordance with the `dp_${dpCode}_${enumValue}`
    dp_fault_0: 'Binary first bit is faulty', // Bitmap type datapoint related multi language should be in accordance with the `dp_${dpCode}_${bit}`
    dp_fault_1: 'Binary second bit is faulty',
  },
  zh: {
    dsc_edit: '编辑', //  基础多语言以 dsc_ 开头并命名语义化即可
    dsc_countdown_on: '设备将在{0}后开启',
    dp_switch: '开关', // 功能点(DP)相关多语言需按照 `dp_${dpCode}` 进行命名
    dp_switch_on: '开关开', // 布尔类型功能点状态相关多语言需按照 `dp_${dpCode}_${'on' || 'off'}` 进行命名
    dp_mode_smart: '智能模式', // 枚举类型功能点状态相关多语言需按照 `dp_${dpCode}_${enumValue}` 进行命名
    dp_fault_0: '第一位故障', // Bitmap 类型功能点状态相关多语言需按照 `dp_${dpCode}_${bit}` 进行命名
    dp_fault_1: '第二位故障',
  }
};

I18N API

以下示例所使用的多语言数据源来自于上方多语言 Key 命名规范区块。

getLang

/**
 * @desc 获取基础多语言
 * @param {String} key - 多语言字段
 * @returns {String} 具体多语言值
 */
// en: Edit; zh: 编辑; 如果找不到: i18n@dsc_edit;
Strings.getLang('dsc_edit');

getDpLang

/**
 * @desc 获取 DP 多语言
 * @param {String} dpCode - dpCode 名
 * @param {String|Number} value - dp 点值
 * @returns {String} 具体多语言值
 */
// en: Smart Mode; zh: 智能模式; 如果找不到: dp_mode_smart;
Strings.getDpLang('mode', 'smart');

formatValue

/**
 * @desc 格式化拼接多语言
 * @param {String} key - 多语言字段
 * @param {...String|Number} values - 需要匹配替换的值,可以为多个
 * @returns {String} 具体多语言值
 */
// en: Turn on after 1 minute; zh: 设备将在1分钟后开启; 如果找不到: 空字符;
Strings.formatValue('countdown_on', '1分钟');

如何在 IoT 平台上传多语言

仅支持大小小于 1M 的 JSON 文件,此外注意在 涂鸦 IoT 平台 上传的多语言优先级比本地代码定义的优先级高。

  1. 找到上传多语言区块。

  2. 点击上传多语言。

  3. 上传如以下 JSON 格式的中英文多语言文件即可,请注意保证 JSON 文件格式的正确性。

    {
      "en": {
        "hello": "Hello"
      },
      "zh": {
        "hello": "你好"
      }
    }