我可以在 json 数据中使用 i18n 资源包吗?

Can I use i18n resource bundle within json data?

我有一个 SAPUI5 (V1.24) master-detail 应用程序,其中我必须显示大约 25 个静态项目的列表,并且每个项目在单击时显示静态图像。

我将列表标题存储在一个 i18n 文件中,该文件在 Component.js 文件中实例化为 ResourceBundle

现在我想知道是否可以将所有标题存储在 JSON 下的 JSON 文件中,而不是在我的 Master.xml.view 文件中添加 25 行 StandardListItem objects 16=] 文件夹并将 JSONModel 绑定到我的 sap.m.List。但是由于我的 JSON "key":"value" 中的值只不过是列表标题,所以我一直在寻找一种方法来将 i18n 文本与 JSON 绑定。像这样:

{
  "List": [
    {
      "Key": "'{i18n>value1}'"
    },
    {
      "Key": "'{i18n>value2}'"
    },
    ...
  ]
}

但它在运行时不起作用。相反,它显示值 as-is,如下所示:

在视图中添加尽可能多的列表项感觉不对。如果明天列表从 25 增加到 50 怎么办?请帮忙。

谢谢。

经过我们的聊天讨论,我提出了以下解决方案

var aAllKeys = [],
    aMasterKeys = [],
    oProperties = {},
    oJSON = {
        items: []
    };
// Get the current locale (for example "de-DE")
var sCurrentLocale = sap.ui.getCore().getConfiguration().getLanguage();
// This creates an array of locale fallback solutions.
// For example ["de-DE", "de", "en", ""]
var aFallbacks = jQuery.sap.resources._getFallbackLocales(sCurrentLocale);
// iterate all locales
for (var i = 0; i < aFallbacks.length; ++i) {
    var sLocale = aFallbacks[i];
    // try to load i18n file for each locale
    oProperties = jQuery.sap.properties({
        url: "i18n/i18n" + (sLocale ? "_" + sLocale : "") + ".properties"
    });
    // if the i18n file exists (i. e. contains keys)
    if (oProperties.getKeys().length > 0) {
        aAllKeys = oProperties.getKeys();
        break;
    }
}

// find all keys of items to display in master (the prefixed ones)
for (i = 0; i < aAllKeys.length; ++i) {
    if (aAllKeys[i].indexOf("MyPrefix.") > -1) {
        aMasterKeys.push(aAllKeys[i]);
    }
}

// find all values of items to display in master
for (i = 0; i < aMasterKeys.length; ++i) {
    oJSON.items.push({
        key: aMasterKeys[i],
        value: oProperties.getProperty(aMasterKeys[i])
    });
}

然后您可以使用 oJSON 创建一个新的 JSON 模型,该模型可以绑定到您的主列表


编辑:我修改了片段的开头。如果当前语言环境没有 i18n 文件,这将添加一个后备解决方案。这是针对 SAPUI5 v1.30 测试的。

参见我在类似主题中提供的解决方案:

最好的部分,它只需要一个单行辅助方法:-)