描述:将UI中的文本移至单独资源文件,以便统一管理(翻译等)
新建webapp/i18n/i18n.properties
showHelloButtonText=Say Hello
helloMsg=helloMsg {0}
helloMsg=helloMsg {0}:{0}为占位符 //通过在花括号中添加数字来向文本添加任意数量的参数。这些数字对应于访问参数的顺序(从 0 开始) //通过getText的第二个参数将部分文本替换为非静态数据在本教程中,我们将只有一个属性文件。但是,在实际项目中,您将为每种受支持的语言创建一个单独的文件,并带有区域设置的后缀,例如 i18n_de.properties德语、i18n_en.properties 英语等。当用户运行应用程序时,SAPUI5将加载最适合用户环境的语言文件。
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:function(){
//将数据模块放入视图
const oData = {
recipient : {
name : "sRecipient"
}
};
const oModel = new JSONModel(oData);
this.getView().setModel(oModel);
//将i18n模块放入视图
const i18nModel = new ResourceModel({
bundleName:"ui5.walkthrough.i18n.i18n"
});
this.getView().setModel(i18nModel,"i18n");
},
onShowHello:function(){
//从视图中读取绑定的模块资源
const oBundle = this.getView().getModel("i18n").getResourceBundle();
const sRecipient = this.getView().getModel().getProperty("/recipient/name");
const sMsg = oBundle.getText("helloMsg",[sRecipient]);
MessageToast.show(sMsg);
}
});
});
webapp/view/App.view.xml
<mvc:View
controllerName="ui5.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>
效果:
- 数据变化
- 数据绑定:实时变化
value="{/recipient/name}"
- 调用函数onShowHello:每次调用时更新变量sRecipient
const sRecipient = this.getView().getModel().getProperty("/recipient/name");
- 数据绑定:实时变化