Implementing i18n (internationalization) in PhoneGap or Cordova Application

Posted By : Akhil Dhiman | 01-Jul-2014

How i18n Works

i18n gets the locale, language from the user mobile settings. There is difference between locale and language. Locale is use to get the time dates and time difference of mobile settings where as language determined what language is your system using i.e. in which format text is appearing and it is independent of locale settings. After getting language you can perform what ever operations to perform on network specific.

Implementation of i18n in Cordova:

To install plugin follow following steps

  • Go to Application root folder.
  • Execute the following command:
    cordova plugin add org.apache.cordova.globalization
  • Make an folder with name i18n in www directory which contain language specific file name strings.json. Please refer Image
  • You can add any no of languages in this folder just add language initials and add strings.json files in it.
  • In strings.json files make all text strings that you want to use in your application.

Now in device ready event add the following code to get language

 var cLANGUAGE = "";
navigator.globalization.getPreferredLanguage(
    //Get Language from Settings
    function (locale) {
        cLANGUAGE = locale.value;
    },
    //On Failure set language to english
    function () {cLANGUAGE = "en";}
 );
 
  • Now, as locale gets your prefered language.
  • For example, If your language is spanish it will return you español(Android) or es(ios).
  • Now in HTML make some unique class like for example "languagespecificHTML","languageSpecificPlaceholder","languageSpecificValue".
  • Add "languagespecificHTML" class into HTML Tags you want to add Language Specific text.
  • Add "languageSpecificPlaceholder" class into HTML Tags you want to add Language Specific PlaceHolder.
  • Add "languageSpecificValue" class into HTML Tags you want to add Language Specific PlaceHolder.

Please Refer Following strings.json file sample

 {
    "languageSpecifications": [
        {
            "username": "Please Enter your user name",
            "password": "Please enter your password",
            "headingtext": "Please Fill Details",
            "submit": "Go"
        }
    ]
}
 

Please Refer Following HTML.

 <!DOCTYPE html>
<html lang="en">
	<head>
		<title>i18n</title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width; initial-scale=1.0">
	</head>
	<body>
		<div>
			<form method="post">
				<span class="languagespecificHTML" data-text="headingtext">Please Enter Username and Password</span>
				<input type="text" id="uname" data-text="username" class="languageSpecificPlaceholder" placeholder="Enter your Username" />
				<input type="password" id="pass" data-text="password" class="languageSpecificPlaceholder" placeholder="Enter your Password" />
				<input type="submit" id="submit" data-text="submit" class="languageSpecificValue" value="Submit" />
			</form>
		</div>
	</body>
</html>
 

In the above attribute make sure that your data attribute i.e. data-text must be same as keys in strings.json

  • After then add the following code to your script file in device ready event
 var cLANGUAGE = null;
navigator.globalization.getPreferredLanguage(
    //Get Language from Settings
    function (locale) {
        cLANGUAGE = locale.value;
        languageControls(cLANGUAGE);
    },
    //On Failure set language to english
    function () {cLANGUAGE = "en";}
);

var languageSpecificObject = null;
var languageSpecificURL = "";
var spanishLanguageSpecificURL = "i18n/es/strings.json";
var englishLanguageSpecificURL = "i18n/en/strings.json";

//Function to make network call according to language on load
var languageControls = function(language){
	if((language.toString() == "es") || (language.toString() == "español") || (language.toString().indexOf("es") != -1)){
            languageSpecificURL = spanishLanguageSpecificURL;
	}
	else{
            //Default English
            languageSpecificURL = englishLanguageSpecificURL;
	}
        //Make an ajax call to strings.json files
	onNetworkCall(languageSpecificURL,function(msg){
   		languageSpecificObject = JSON.parse(msg);
		$(".languagespecificHTML").each(function(){
			$(this).html(languageSpecificObject.languageSpecifications[0][$(this).data("text")]);
		});
		$(".languageSpecificPlaceholder").each(function(){
			$(this).attr("placeholder",languageSpecificObject.languageSpecifications[0][$(this).data("text")]);
		});
                $(".languageSpecificValue").each(function(){
			$(this).attr("value",languageSpecificObject.languageSpecifications[0][$(this).data("text")]);
		});
	});
};

//Function to get specific value with unique key
var getLanguageValue = function(key){
	value = languageSpecificObject.languageSpecifications[0][key];
	return value;
};

//Network Call
var onNetworkCall = function(urlToHit,successCallback){
    $.ajax({
       type: "POST",
       url: urlToHit,
       timeout: 30000 ,
       }).done(function( msg ) {
           successCallback(msg);
               }).fail(function(jqXHR, textStatus, errorThrown){
                   alert("Internal Server Error");
               });
}
 

 

  • After getting success from the network call it call successcallback function and the above .each loops will change the HTML, Placeholder, Value of the tags in HTML i.e. HTML will change to the following HTML
 <!DOCTYPE html>
<html lang="en">
	<head>
		<title>i18n</title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width; initial-scale=1.0">
	</head>
	<body>
		<div>
			<form method="post">
				<span class="languagespecificHTML" data-text="headingtext">Please Fill Details</span>
				<input type="text" id="uname" data-text="username" class="languageSpecificPlaceholder" placeholder="Please Enter your user name" />
				<input type="password" id="pass" data-text="password" class="languageSpecificPlaceholder" placeholder="Please enter your password" />
				<input type="submit" id="submit" data-text="submit" class="languageSpecificValue" value="Go" />
			</form>
		</div>
	</body>
</html>>
 
  • If you want to get any specific value of a key through function inside javascript use the following function.
 getLanguageValue("headingtext");
 

Thanks

 

About Author

Author Image
Akhil Dhiman

Akhil is an iPhone and Android application developer with experience in PhoneGap and Swift(Native iOS). Akhil has good experience working with JavaScript, jQuery and Underscore as well.

Request for Proposal

Name is required

Comment is required

Sending message..