-->

How to use “formatMessage” module with i18n model

2020-07-29 17:33发布

问题:

In the UI5 Demo Kit, Walkthrough step 8 (still) mentions the following:

To be on the safe side, we would have to use a similar mechanism as in the controller to use a string from the resource bundle and replace parts of it. This can be done with the jQuery.sap.formatMessage formatter.

It can be used for translatable texts with placeholders in XML views e.g.:

<Title text="{
  parts: [
    'i18n>overflowToolbarTitle',
    'appView>/listItemCount'
  ],
  formatter: 'jQuery.sap.formatMessage'
}" />

However, jQuery.sap.formatMessage is depreciated since 1.58, and if I use instead the suggested alternative sap.base.strings.formatMessage, the following error is thrown:

formatter function sap.base.strings.formatMessage not found!

How can the new formatMessage module be used in XML?

回答1:

UI5 1.69+

With commit:2dab48e, it is now possible to require modules declaratively in XML views:

<Title xmlns="sap.m" xmlns:core="sap.ui.core"
  core:require="{ formatMessage: 'sap/base/strings/formatMessage' }"
  text="{
    parts: [
      'i18n>overflowToolbarTitle',
      'appView>/listItemCount'
    ],
    formatter: 'formatMessage'
  }"
/>

With this, we can avoid having dependency to an intermediate Controller and make use of the new module independently.


UI5 1.68 and below (previous answer)

UI5 currently doesn't allow fetching and assigning a module to the formatter.1 Furthermore, the new function module is never exported with the name sap.base.strings.formatMessage.src

One of the alternative approaches would be to point to the method assigned in the controller whereas that method points to the required formatMessage module.

<Title text="{
  parts: [
    'i18n>overflowToolbarTitle',
    'appView>/listItemCount'
  ],
  formatter: '.formatMessage'
}"/>
sap.ui.define([
  "sap/ui/core/mvc/Controller",
  "sap/base/strings/formatMessage",
  // ...
], function(Controller, formatMessage/*, ...*/) {
  "use strict";

  return Controller.extend("...", {
    formatMessage: formatMessage,
    // ...
  });
})

I could imagine that UI5 supports fetching and assigning modules within binding definition in later versions, but at the time of writing it's not possible.



1 Related enhancement request: https://github.com/SAP/openui5/issues/2475



标签: sapui5