1. 程式人生 > 其它 >Step 8: Translatable Texts

Step 8: Translatable Texts

轉載請聯絡vx:xiaoshitou5854

把畫面表示的文字抽離出來,放到單獨的檔案,以適應國際化要求。

ui5會根據瀏覽器發發給server的國家區域資訊,返回給瀏覽器相應語言的properties

webapp/i18n/i18n.properties (New)

showHelloButtonText=Say Hello
helloMsg=Hello {0}

{0}是引數。

實際專案裡,每個國家的語言都是一個單獨的檔案,例如檔名字是i18n_de.properties(德語) i18n_en.properties(英語)

controller/App.controller.js

sap.ui.define([
   "sap/ui/core/mvc/Controller",
   "sap/m/MessageToast",
   "sap/ui/model/json/JSONModel",
   "sap/ui/model/resource/ResourceModel"
], function (Controller, MessageToast, JSONModel, ResourceModel) {
   "use strict";
   return Controller.extend("sap.ui.demo.walkthrough.controller.App", {
     onInit : function () {
         // set data model on view
         var oData = {
            recipient : {
               name : "World"
            }
         };
         var oModel = new JSONModel(oData);
         this.getView().setModel(oModel);
         // set i18n model on view
         var i18nModel = new ResourceModel({
            bundleName: "sap.ui.demo.walkthrough.i18n.i18n"
         });
         this.getView().setModel(i18nModel, "i18n");
      },
      onShowHello : function () {
         // read msg from i18n model
         var oBundle = this.getView().getModel("i18n").getResourceBundle();
         var sRecipient = this.getView().getModel().getProperty("/recipient/name");
         var sMsg = oBundle.getText("helloMsg", [sRecipient]);
         // show message
         MessageToast.show(sMsg);
      }
   });
});
  • 初始化i18n的時候,指定的bundleName: "sap.ui.demo.walkthrough.i18n.i18n"的意思:sap.ui.demo.walkthrough是app的名字,在index.html定義的,第一個i18n是資料夾名字,第二個i18n是檔名字,省略的檔案的字尾名
  • this.getView().setModel(i18nModel, "i18n1"):把i18nMod放到view裡,並給個i18n1名字。這個model可以用this.getView().getModel("i18n1")取得
  • this.getView().getModel().getProperty("/recipient/name"):取得畫面value為/recipient/name的值
  • oBundle.getText("helloMsg", [sRecipient]):從i18n檔案裡,取得key為helloMsg的字串,[sRecipient])為helloMsg的字串的引數(helloMsg=Hello {0})

webapp/view/App.view.xml

<mvc:View
   controllerName="sap.ui.demo.walkthrough.controller.App"
   xmlns="sap.m"
   xmlns:mvc="sap.ui.core.mvc">
   <Button
      text="{i18n>showHelloButtonText}"
      press=".onShowHello"/>
   <Input
      value="{/recipient/name}"
      description="Hello {/recipient/name}"
      valueLiveUpdate="true"
      width="60%"/>
</mvc:View>

  • text="{i18n>showHelloButtonText}":從i18n取得字串

本人微信:xiaoshitou5854