在这个章节,我们会将一些文本常量独立出一个资源文件
这样的话,可以方便这些文本常量被翻译成任意的语言
这种国际化的操作,我们一般命名为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.