SAP OPEN UI5 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

原文地址:https://www.cnblogs.com/xiaoshiwang/p/14920390.html