+

Search Tips   |   Advanced Search

Globalization mechanisms in IBM MobileFirst Platform Foundation

IBM MobileFirst Platform Foundation automatically translates application strings according to a designated file. Multi-language translation is implemented using JavaScript.


Cordova globalization API

The Cordova globalization API provides enhanced globalization capabilities that mirror existing JavaScript globalization functions, where possible, without duplicating functions already present in JavaScript. The emphasis of the Cordova globalization API is on parsing and formatting culturally sensitive data. The Cordova API uses native functions in the underlying operating system, where possible, rather than re-creating these functions in JavaScript. Table 1 summarizes the Cordova globalization API functions provided.

Function Name Purpose
getPreferredLanguage The current language of the client.
getLocaleName The client current locale setting on the device.
dateToString A date that is formatted as a string, according to the locale and timezone of the client.
stringToDate A string that is parsed as a date, according to the client's user preferences.
getDatePattern A pattern string for formatting and parsing dates.
getDateNames The names of the months, or the days of the week.
isDayLightSavingsTime Whether daylight saving time is in effect for a specified date.
getFirstDayOfWeek The first day of the week.
numberToString A number that is formatted as a string, according to the user preferences.
stringToNumber A string that is parsed as a number, according to the user preferences.
getNumberPattern A pattern string for formatting and parsing numbers.
getCurrencyPattern A pattern string for formatting and parsing currencies.

The Cordova globalization API is an independent globalization framework, which can be integrated with any JavaScript libraries to provide globalization functions. The Cordova globalization API is different from other globalization libraries. The Cordova globalization API does not provide a parameter to indicate a locale. The set of supported locales is determined by the device and its SDK and not by Cordova.

The Cordova globalization API uses the client locale setting and any default values that are overridden. This design greatly simplifies the use of the globalization API while still providing robust support. It is important to note that, although the set of interfaces remains constant across the devices that Cordova supports, the results can vary across the devices.

The Cordova framework does not provide access to graphical widgets that are present in device SDKs. The Cordova framework is used in concert with other JavaScript widget libraries, such as Dojo, to build complete mobile applications. The Cordova globalization API is interoperable with Dojo Mobile, jQuery Mobile, and Sencha Touch. It is an asynchronous implementation to prevent blocking JavaScript execution in user interface code. The following listings and figures show the Cordova globalization API. Dojo is used to demonstrate the user interface.

function onDeviceReady(){
  g11n = window.plugins.globalization;
}

The code to generate the names of the months, days of the week, and format the current date is shown in Listing 2, Listing 3, and Listing 4.

function getMonths(){
  g11n.getDateNames(function(data){
    var items = data.value;
    var monthsView = document.getElementById('monthsView');
    for (var i = 0; i < items.length; i++) {
      monthsView.append('<li>' + items[i] + '</li>');
    }
  },   function(code){
    alert("Error: " + code);
  });
};

Figure 1. Using Cordova to show locale-based months

function getDays(){
  g11n.getDateNames(
    function(data){
      var items = data.value;
      var daysView = document.getElementById('daysView');
      for (var i = 0; i < items.length; i++) {
        daysView.append('<li>' + items[i] + '</li>');
    }, function(code){
      alert("Error: " + code);
    }, {item: "days"}
  );
}

Figure 2. Using Cordova to show the days of week

function getFormats(){
  var formatsView = document.getElementById('formatsView');
  g11n.dateToString(
    new Date(), function(date){
      formatsView.append('<li>' + date.value + '</li>');
    }, function(code){
      alert("Error: " + code);
    }, {selector: "date", formatLength: "full"}
  );
  g11n.getDatePattern(
    function(date){
      formatsView.append('<li>' + date.pattern + '</li>');
      var timeZone = date.timezone;
      formatsView.append('<li>' + timeZone + '</li>');
      var offset = date.utc_offset;
      formatsView.append('<li>' + offset + '</li>');
      var dstoffset = date.dst_offset;
      formatsView.append('<li>' + dstoffset + '</li>');
    }, function(code){
      alert("Error: " + code);
    }, {selector: "date", formatLength: "full"}
  );
  g11n.isDayLightSavingsTime(
    new Date(), function(date){
      var dst = date.dst;
      formatsView.append('<li>' + dst + '</li>');
    }, function(code){
      alert("Error: " + code);
    }
  );
  g11n.numberToString(
    1234.56, function(number){
      formatsView.append('<li>' + number.value + '</li>');
    }, function(code){
      alert("Error: " + code);
    }, {type: "decimal"}
  );
}

Figure 3. Using Cordova for cultural formatting


Enable translation of application strings

messages.js is the file that is designated for application strings and can be found in the common/js folder. If we use Dojo, jQuery, or Sencha Touch in the application, use the translation resource loading mechanisms and file formats from these JavaScript technologies instead of mechanisms provided by MPF. Use MobileFirst application messages only when the JavaScript graphical toolkit used in the application does not provide these services.

Messages = {
  headerText: "Default header",   actionsLabel: "Default action label",   sampleText: "Default sample text",   englishLanguage: "English",   frenchLanguage: "French",   (...)
}
Application messages stored in messages.js can be referenced in two ways:

A string defined in Messages.headerText is automatically used here.


Enable translation of system messages

We can enable the translation of the system messages that the application displays, such as Internet connection is not available, or Invalid user name or password.

We can find the list of the system messages in the worklight/messages/messages.json file that is in the environment folder of the projects that you generated with MPF.

To enable the translation of a system message, we must override its value in the WL.ClientMessages object, as indicated in The WL.ClientMessages object.


Implementing multi-language translation

We can implement multi-language translation for the applications using JavaScript.

  1. Define default application strings in messages.js as shown in the following code example:
    Messages = {
      headerText: "Default header",   actionsLabel: "Default action label",   sampleText: "Default sample text",   englishLanguage: "English",   frenchLanguage: "French",   russianLanguage : "Russian",   hebrewLanguage : "Hebrew"
    };

  2. Override some or all of the default application strings with JavaScript. The following two code examples define JavaScript functions used to override the default strings that are defined in messages.js:
    function setFrench(){
      Messages.headerText = "Traduction";
      Messages.actionsLabel = "Sélectionnez langue:";
      Messages.sampleText = "ceci est un exemple de texte en français.";
    }
    function setRussian(){
      Messages.headerText = "Перевод";
      Messages.actionsLabel = "выбoр языкa:";
      Messages.sampleText = "это пример текста на русском языке.";
    }
    function languageChanged(lang){
      if (typeof(lang)!="string") lang = $("#languages").val();
      switch (lang){
        case "english":
          setEnglish();
          break;
        case "french":
          setFrench();
          break;
        case "russian":
          setRussian();
          break;
        case "hebrew":
          setHebrew();
          break;
    if ($("#languages").val()=="hebrew") 
      $("#AppBody").css({direction: 'rtl'});
    else 
      $("#AppBody").css({direction: 'ltr'});
      $("#sampleText").html(Messages.sampleText);
      $("#headerText").html(Messages.headerText);
      $("#actionsLabel").html(Messages.actionsLabel);
    }

A language parameter is passed to the languageChanged() JavaScript function. The languageChanged() function calls the corresponding function to override the default English language string.


Detecting device-specific information

We can detect the locale and language of the device using WL.App.getDeviceLocale() and WL.App.getDeviceLanguage().

var locale = WL.App.getDeviceLocale();
var lang = WL.App.getDeviceLanguage();
WL.Logger.debug(">> Detected locale: " + locale);
WL.Logger.debug(">> Detected language: " + lang);

The following screen capture shows the print output:


Parent topic: Develop globalized hybrid applications