【快應用】多語言適配案例

 【關鍵詞】

多語言,$t

 

【問題背景】

快應用平臺的能力會覆蓋多個國家地區,平臺支持多語言的能力後,可以讓一個快應同時支持多個語言版本的切換,開發者無需開發多個不同語言的源碼項目,避免給項目維護帶來困難。使用系統默認的語言,開發者配置多語言的方式非常簡單,只需要定義資源與引用資源兩個步驟即可

 

【實現方案】

多語言的實現主要分爲兩步:

1、資源文件的定義,即資源文件的創建

資源文件用於存放多個語言的業務信息定義,快應用平臺使用JSON文件保存資源定義。

在項目源碼src目錄下定義i18n文件夾,內部放置每個語言地區下的資源定義文件即可。多個資源文件會按一定順序進行匹配,例如:對於zh-CN,則按zh-CN -> zh -> zh-* -> defaults的順序匹配,其中zh-*匹配到多個,則按字母升序區分大小寫排序。

如下圖所示:

zh-CN.json

cke_10022.png

en-US.json

cke_12257.png

2、 多語言的引用方式

2.1、Ux頁面中使用;

可以template中使用$t("hello.text")方式直接使用json文件中配置的,也可以通過{{ $t("hello.content", { txt: data }) }}使用變量data的方式去使用。

<template>

  <!-- Only one root node is allowed in template. -->

  <div class="container">

    <text class="title">{{ $t("hello.text") }}</text>

    <text>{{ $t("hello.content", { txt: data }) }}</text>

  </div>

</template>

 

<style>

  .container {

    flex-direction: column;

    justify-content: center;

    align-items: center;

  }

 

  .title {

    font-size: 100px;

  }

</style>

 

<script>

  import configuration from '@system.configuration'

  module.exports = {

    data: {

      componentData: {},

      data: ""

    },

    onShow(options) {

      console.log(this.$t("hello.text"));

      const locale = configuration.getLocale()

      console.log(locale.language)

      if (locale.language === "zh") {

        this.data = "歡迎使用多語言示例"

      } else if (locale.language === "en") {

        this.data = "welcome to use Multilingual demo"

      }

    },

  }

</script>

截圖:

cke_4086.png

2.2、Manifest文件中配置,用法是${xxx.xxx}形式,下面展示了在manifest文件中應用名稱和頁面標題的多語言配置,對應的配置可以看上圖的json文件。

{

  "package": "com.huawei.language",

  "name": "${message.appName}",

  "versionName": "1.0.0",

  "versionCode": 1,

  "icon": "/Common/logo.png",

  "minPlatformVersion": 1100,

  "features": [],

  "config": {},

  "router": {

    "entry": "Hello",

    "pages": {

      "Hello": {

        "component": "hello"

      }

    }

  },

  "display": {

    "pages": {

      "Hello": {

        "titleBarText": "${hello.helloTitlebar}"

      }

    }

  }

}

截圖:

cke_7995.png

 

 欲瞭解更多更全技術文章,歡迎訪問https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章