Menu

04 October 2009

Client Side UI localisation of WebApplications using JSON and Javascipt

If you have made any web application or website and you want to have UI localisation for many language then you can do with following technique.

Step 1 - put id on tags which need to local language string like
<h1 id="helloworld">Hello World</h1>
<img title="Click here to draw" src="http://www.blogger.com/sample.png" id="clicktodraw" />

Step 2 - make language files in json format.
[
{"id":"helloworld" "textContent":"दुनिया नमस्ते"},
{"id":"clicktodraw" "title":"खींचने के लिए यहां क्लिक करें"}
]

save it as - locale/lang.hi.js
if you want French translation then put French translated string and save it as locale/lang.fr.js
Step 3 -
Download locale.js from http://svg-edit.googlecode.com/svn-history/r757/trunk/editor/locale/locale.js and save it as locale/locale.js
This is the current content of locale.js

function gup( name )
{
//Function GUP is taken from http://www.netlobo.com/url_query_string_javascript.html
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}

var put_locale = function(){

var lang_param = gup("lang");
if(lang_param ==""){
return;
}
var url = "locale/lang." + lang_param + ".js";
$.get(url,
function(data){
var LangData = eval(data);
for (var i=0;i<LangData.length;i++)
{
var elem = document.getElementById(LangData[i].id);
if(elem){
if(LangData[i].suffice){
if(LangData[i].title){elem.title=LangData[i].title +LangData[i].suffice ;}
if(LangData[i].textContent){elem.textContent=LangData[i].textContent +LangData[i].suffice ;}
}
else{
if(LangData[i].title){elem.title=LangData[i].title;}
if(LangData[i].textContent){elem.textContent=LangData[i].textContent;}
}//end suffice
}
}
},"json");
};//function end

Include locale.js and jQuery API into your web application.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="locale/locale.js"></script>

Step 4 -
call put_locale() function after the DOM is available.

$(function() {
put_locale();
//Rest of the coding ..
});


You are done. Whenever you want translated localised GUI for your application, all you need to add url parameter to your application like
http://example.org/myapplication/html?lang=hi


If you want to see code then you can see How Svg-Edit use this technique the you can see our source code -
http://code.google.com/p/svg-edit/source/browse/trunk/editor/locale/
Post a Comment