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

How is localized data binding set up with JSON files and XML views?

我有一个 XMLView 主页,其中包含一些磁贴。这些图块是从 JSON 文件中填充的。磁贴具有 'title' 属性,需要 i18n 数据绑定。

XML 视图的一部分:

<TileContainer id="container" tiles="{/TileCollection}">
  <StandardTile
   icon="{icon}"
   title="{title}"
   press="onPress" />
</TileContainer>

JSON 文件:

{
  "TileCollection" : [
      {
          "icon"   : "sap-icon://document-text",
          "title"  : "{i18n>foo}"
      }, 
      ... etc

我完成数据绑定的旧方法是直接在视图中使用 title="{i18n>foo}"。当然,现在我基本上有两层数据绑定,一层在 JSON 中用于 i18n,一层在视图中以获取 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");
}

这个问题源于对另一个问题的讨论,因此可能会有更多信息供感兴趣的人使用。

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

例如,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>

(注意属性 titleinfo 的格式化程序函数 getI18nValue;这些是要翻译的属性。其他属性按原样来自绑定的 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"
    }
]

其中 JSONModel 的 titleinfo 属性 值(例如,'inbox' 和 'overdue')对应于资源包中的键文件(以及您的 ResourceModel)

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

getI18nValue : function(sKey) {
    return this.getView().getModel("i18n").getProperty(sKey);
}

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