多语言,相当于SAP GUI中的数据元素的translate,WEB应用的SOTR_EDIT
把UI中的文本放到一个单独的文件中,这样集中进行维护,方便翻译至其它语言。
这个国际化的过程简称 i18n( internationalization 这个单词,取首位两个字母,中间字母数为18), 在SAPUI5中通过数据绑定来绑定一种特殊的resource model来实现的,区别是绑定时前面没有 /
。
在step8的基础上新建一个i18n
文件夹和一个i18n.properties
文件
webapp/i18n/i18n.properties
showHelloButtonText=Say Hello
helloMsg=Hello {0}
下面是i18n model的一些要求:
- 所谓的i18n Model就是一种Resource Model
- 默认的文件名是i18n.properties,多语言下需要每一种语言保存成一个文件,如i18n_en.properties,i18n_de.properties
- Resource bundle中的键一般用首字母小写的驼峰式写法
- Resource bundle中的值可以包含变量参数,如{0}, {1}, {2}, …
- 不要使用拼接的方式进行翻译,使用占位符
- 特殊字符使用Unicode
示例中i18n.properties文件中的声明了两个键值,第2个使用了占位符{0}(要注意使用的顺序,从0 开始依次使用)
webapp/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("Step8_i18n.controller.App", {
onInit: function() {
var oData = {
recipient: {
name: "world"
}
};
var oModel = new JSONModel(oData);
this.getView().setModel(oModel, "aaa");
//set i18n Model to view
var i18nModel = new ResourceModel({
bundleName: "Step8_i18n.i18n.i18n"
});
this.getView().setModel(i18nModel,"i18n");
},
onClickMe: function(oEvent) {
//read from i18n Model
var oBundle = this.getView().getModel("i18n").getResourceBundle();
var sRecipient = this.getView().getModel("aaa").getProperty("/recipient/name");
var sMsg = oBundle.getText("helloMsg",[sRecipient]);
MessageToast.show(sMsg);
//This code was generated by the layout editor.
//MessageToast.show("you Clicked me!");
}
});
});
这里添加了两块内容:
- onInit事件中加入
//set i18n Model to view
var i18nModel = new ResourceModel({
bundleName: "Step8_i18n.i18n.i18n"
});
this.getView().setModel(i18nModel, "i18n");
var i18nModel = new ResourceModel(...)
声明一个ResourceModel对象,指定bundleName属性为"Step8_i18n.i18n.i18n"
,也就是指定properties文件的路径。
this.getView().setModel(i18nModel, "i18n");
将Model指定给View。
2. onClickMe事件中加入
var oBundle = this.getView().getModel("i18n").getResourceBundle();
var sRecipient = this.getView().getModel("aaa").getProperty("/recipient/name");
var sMsg = oBundle.getText("helloMsg", [sRecipient]);
MessageToast.show(sMsg);
var oBundle = ...
取当前view的ResourceBundle
var sRecipient = ...
取view中输入框的内容,因为是双向绑定,所以只需要取对应model的property即可。
var sMsg = ...
取ResourceBundle中键为"helloMsg"
的值 ,[sRecipient]
就是值中的参数{0}
,如果properties文件中有多个参数,这里可以依次调用替换。
如下面示例,我又在i18n.properties文件中加了一个键值对
newText=aaaaa {0} {1}
在按钮的点击事件中这么写
var aStr = "bbbb";
var sMsg1 = oBundle.getText("newText", [sRecipient,aStr]);
MessageToast.show(sMsg1);
最终就会显示 aaaaa World bbbb