Managing multiple languages with Appcelerator Titanium

Titanium provides a number of JavaScript functions in the Titanium.Locale namespace for use in localization. It also provides String formatting functions to handle dates, times, currencies, and more. You can even internationalize the name of your app itself. There’s a good tutorial on how to do this here. Titanium also allows you to define internationalization files and automatically chooses the correct one based on device locale settings. But what if you want to allow the user to choose the language for the app from within the application settings? To provide this functionality in an app built with Titanium, we would need to override the function L() that Titanium uses to retrieve localised strings from one of the xml files. Here, we will parse the xml files manually based on the user’s selected language and find the localised string that user is looking for.

/**
 * Returns the text based on the selected language in the application settings.
 */
function L(text) {
  if (Ti.App.languageXML === undefined || Ti.App.languageXML === null) {
    var langFile = Ti.App.Properties.getString('SETTING_LANGUAGE'); // We should store user's language setting in SETTING_LANGUAGE
    var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'i18n/' + langFile + '.xml'); // Get the corresponding file from i18n
    if (!file.exists()) {
      var langFile = "en"; // Fall back to english as the default language
      file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'i18n/' + langFile + '.xml');
    }
    var xmltext = file.read().text;
    var xmldata = Titanium.XML.parseString(xmltext); // Parse the xml
    Ti.App.languageXML = xmldata; // Store the parsed xml so that we don't parse everytime L() is called
  }
  // Get the localised string from xml file
  var xpath = "/resources/string[@name='" + text + "']/text()"; 
  var result = Ti.App.languageXML.evaluate(xpath).item(0);
  if (result) {
    return result.text;
  } else {
    return text; // Return the text if localised version not found
  }
}

Now, all you need is to include this in every file and whenever you want to use a localised string, use L('my-string-here') in its place. Don’t forget to set the currently selected language using Ti.App.Properties.setString('SETTING_LANGUAGE','en'); All that’s left now is to create your internationalisation files in i18n directory inside your app resources and declare strings in the following format:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <string name="home">Home</string>
  <string name="settings">Settings</string>
</resources>
Published 17 Nov 2012

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter