在這個章節,我們會將一些文本常量獨立出一個資源文件
這樣的話,可以方便這些文本常量被翻譯成任意的語言
這種國際化的操作,我們一般命名為i18n
新建一個文件i18n.properties
webapp/i18n/i18n.properties (New)
showHelloButtonText=Say Hello
helloMsg=Hello {0}
接著我們將這些常量,綁定到Controller.js
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"
], (Controller, MessageToast, JSONModel, ResourceModel) => {"use strict";return Controller.extend("ui5.walkthrough.controller.App", {onInit() {// set data model on viewconst oData = {recipient : {name : "World"}};const oModel = new JSONModel(oData);this.getView().setModel(oModel);// set i18n model on viewconst i18nModel = new ResourceModel({bundleName: "ui5.walkthrough.i18n.i18n"});this.getView().setModel(i18nModel, "i18n");},onShowHello() {// read msg from i18n modelconst oBundle = this.getView().getModel("i18n").getResourceBundle();const sRecipient = this.getView().getModel().getProperty("/recipient/name");const sMsg = oBundle.getText("helloMsg", [sRecipient]);// show messageMessageToast.show(sMsg);}});
});
另外將view.xml中的常量文本替代
webapp/view/App.view.xml
<mvc:ViewcontrollerName="ui5.walkthrough.controller.App"xmlns="sap.m"xmlns:mvc="sap.ui.core.mvc"><Buttontext="{i18n>showHelloButtonText}"press=".onShowHello"/><Inputvalue="{/recipient/name}"description="Hello {/recipient/name}"valueLiveUpdate="true"width="60%"/>
</mvc:View>
Conventions
-
The resource model for internationalization is called the?
i18n
?model. -
The default filename is?
i18n.properties
. -
Resource bundle keys are written in (lower) camelCase.
-
Resource bundle values can contain parameters like?
{0}
,?{1}
,?{2}
, … -
Never concatenate strings that are translated, always use placeholders.
-
Use Unicode escape sequences for special characters.