如何使用JSON文件和XML视图设置本地化数据绑定?

Pry*_*cer 4 javascript sapui5

我有一个包含一些磁贴的XMLView主页.这些切片是从JSON文件填充的.磁贴具有'title'属性,需要i18​​n数据绑定.

XML视图的一部分:

<TileContainer id="container" tiles="{/TileCollection}">
  <StandardTile
   icon="{icon}"
   title="{title}"
   press="onPress" />
</TileContainer>
Run Code Online (Sandbox Code Playgroud)

JSON文件:

{
  "TileCollection" : [
      {
          "icon"   : "sap-icon://document-text",
          "title"  : "{i18n>foo}"
      }, 
      ... etc
Run Code Online (Sandbox Code Playgroud)

我完成数据绑定的旧方法直接在视图中title="{i18n>foo}".当然,现在我基本上有两层数据绑定,一个用于i18n的JSON,另一个用于获取JSON(获取i18n)的视图.

这也是我设置i18n模型的Component.js.

sap.ui.core.UIComponent.extend("MYAPP.Component", {
  metadata: {
    rootView : "MYAPP.view.Home", //points to the default view

    config: {
      resourceBundle: "i18n/messageBundle.properties"
    },
    ... etc


  init: function(){
    sap.ui.core.UIComponent.prototype.init.apply(this, arguments);
    var mConfig = this.getMetadata().getConfig();

    var oRouter = this.getRouter();
    this.RouteHandler = new sap.m.routing.RouteMatchedHandler(oRouter);
    oRouter.register("router");
    oRouter.initialize();

    var sRootPath = jQuery.sap.getModulePath("MYAPP");
    var i18nModel = new sap.ui.model.resource.ResourceModel({
        bundleUrl : [sRootPath, mConfig.resourceBundle].join("/")
    });
    this.setModel(i18nModel, "i18n");
}
Run Code Online (Sandbox Code Playgroud)

这个问题来自于对另一个问题的讨论,因此对于任何感兴趣的人可能会有更多的信息.链接

Qua*_*ure 10

我通常采用的方法是使用格式化程序函数,其唯一目的是为某个键获取正确的本地化值(在资源模型中维护,并由数据模型驱动)

例如,Tile UI看起来像这样:

<TileContainer id="container" tiles="{/tiles}">
    <StandardTile
      icon="{icon}"
      type="{type}"
      title="{ path : 'title', formatter : '.getI18nValue' }"
      info="{ path : 'info', formatter : '.getI18nValue' }"
      infoState="{infoState}" 
      press="handlePress"/>
</TileContainer>
Run Code Online (Sandbox Code Playgroud)

(注意格式化功能getI18nValue对于性能titleinfo;这些是要翻译的性能的其他属性来原样从结合JSONModel)

该模型可能如下所示:

tiles : [
    {
        icon      : "sap-icon://inbox",
        number    : "12",
        title     : "inbox",   // i18n property 'inbox'
        info      : "overdue", // i18n property 'overdue'
        infoState : "Error"
    },
    {
        icon      : "sap-icon://calendar",
        number    : "3",
        title     : "calendar", // i18n property 'calendar'
        info      : "planned",  // i18n property 'planned'
        infoState : "Success"
    }
]
Run Code Online (Sandbox Code Playgroud)

titleinfo该JSONModel的属性值(例如,"收件箱"和"过期")用钥匙对应你的资源包文件(因此你ResourceModel)

控制器中的格式化程序功能(或者更好,在独立的JS文件中,可以在多个视图中重复使用)非常简单:

getI18nValue : function(sKey) {
    return this.getView().getModel("i18n").getProperty(sKey);
}
Run Code Online (Sandbox Code Playgroud)

它只是提供模型中的值(例如,'inbox')并从资源模型返回此键的本地化值