1# 多语言支持 2 3基于开发框架的应用会覆盖多个国家和地区,开发框架支持多语言能力后,可以让应用开发者无需开发多个不同语言的版本,就可以同时支持多种语言的切换,为项目维护带来便利。 4 5开发者仅需要通过[定义资源文件](#定义资源文件)和[引用资源](#引用资源)两个步骤,就可以使用开发框架的多语言能力;如果需要在应用中获取当前系统语言,请参考[获取语言](#获取语言)。 6 7## 定义资源文件 8 9资源文件用于存放应用在多种语言场景下的资源内容,开发框架使用JSON文件保存资源定义。 10 11在[文件组织](js-lite-framework-file.md)中指定的i18n文件夹内放置每个语言地区下的资源定义文件即可,资源文件命名为“语言-地区.json”格式,例如英文(美国)的资源文件命名为en-US.json。当开发框架无法在应用中找到系统语言的资源文件时,默认使用en-US.json中的资源内容。 12 13资源文件内容格式如下: 14 15en-US.json 16 17```json 18{ 19 "strings": { 20 "hello": "Hello world!", 21 "object": "Object parameter substitution-{name}", 22 "array": "Array type parameter substitution-{0}", 23 "symbol": "@#$%^&*()_+-={}[]\\|:;\"'<>,./?" 24 }, 25 26 "files": { 27 "image": "image/en_picture.PNG" 28 } 29} 30``` 31 32## 引用资源 33 34- 在应用中使用$t方法引用资源,$t既可以在hml中使用,也可以在js中使用。系统将根据当前语言环境和指定的资源路径(通过$t的path参数设置),显示对应语言的资源文件中的内容。 35 36 | 参数 | 类型 | 必填 | 描述 | 37 | ------ | ------------- | ---- | ------------------------------------------------------------ | 38 | path | string | 是 | 资源路径 | 39 | params | Array\|Object | 否 | 运行时用来替换占位符的实际内容,占位符分为两种:具名占位符,例如{name}。实际内容必须用Object类型指定,例如:$t('strings.object', **{ name: 'Hello world' }**)。数字占位符,例如{0}。实际内容必须用Array类型指定,例如:$t('strings.array', **['Hello world']**)。 | 40 41- 示例代码 42 43 ```html 44 <!-- xxx.hml --> 45 <div> 46 <!-- 不使用占位符,text中显示“Hello world!” --> 47 <text>{{ $t('strings.hello') }}</text> 48 <!-- 具名占位符格式,运行时将占位符{name}替换为“Hello world” --> 49 <text>{{ $t('strings.object', { name: 'Hello world' }) }}</text> 50 <!-- 数字占位符格式,运行时将占位符{0}替换为“Hello world” --> 51 <text>{{ $t('strings.array', ['Hello world']) }}</text> 52 <!-- 先在js中获取资源内容,再在text中显示“Hello world” --> 53 <text>{{ hello }}</text> 54 <!-- 先在js中获取资源内容,并将占位符{name}替换为“Hello world”,再在text中显示“Object parameter substitution-Hello world” --> 55 <text>{{ replaceObject }}</text> 56 <!-- 先在js中获取资源内容,并将占位符{0}替换为“Hello world”,再在text中显示“Array type parameter substitution-Hello world” --> 57 <text>{{ replaceArray }}</text> 58 59 <!-- 获取图片路径 --> 60 <image src="{{ $t('files.image') }}" class="image"></image> 61 <!-- 先在js中获取图片路径,再在image中显示图片 --> 62 <image src="{{ replaceSrc }}" class="image"></image> 63 </div> 64 ``` 65 66 ```javascript 67 // xxx.js 68 // 下面为在js文件中的使用方法。 69 export default { 70 data: { 71 hello: '', 72 replaceObject: '', 73 replaceArray: '', 74 replaceSrc: '', 75 }, 76 onInit() { 77 this.hello = this.$t('strings.hello'); 78 this.replaceObject = this.$t('strings.object', { name: 'Hello world' }); 79 this.replaceArray = this.$t('strings.array', ['Hello world']); 80 this.replaceSrc = this.$t('files.image'); 81 }, 82 } 83 ``` 84 85 86 87## 获取语言 88 89获取语言功能请参考[应用配置](../js-apis-system-configuration.md)。