Recently, I needed to add a multi-language support to a website that was run using PHP. Sure, I could use some i18n PHP framework to deliver translated web-page directly from a server, but I decided to design a simple approach based on Javascript.
Here it goes …
The default language is supposed to be slovene, so visiting a page by url http://mywebpage would show a slovene version. To get a webpage in a specific language, you need to explicitly define the language using a parameter, like so: http://mywebpage?lang={sl, hr, en}. Of course, this is used in a header of a web page for a languages selection menu:
In the webpage, I introduced a “lang” HTML tag, which acts as a placeholder for a language-specific text:
<lang id="home" />
For each language I create a separate JS file that includes a map variable, whose keys are ids used in HTML placeholders and values are translated texts. For example, a file “lang.sl.js” includes slovene translations:
var lang = {
home: "Domov",
about: "O programu",
functionalities: "Funkcionalnosti",
....
};
Now, as we have everything prepared, we are going to write a JS script that (A) automatically detects a selected language from query string, (B) includes an appropriate translation file and (C) automatically populates prepared HTML placeholders. I do this as follows:
$(document).ready(function() {
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
function loadJS(file) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = file;
$("body").prepend(jsElm);
}
if ($.urlParam("lang") == "en") {
loadJS("js/lang.en.js");
$("#lang-en").css("font-weight", "bolder");
} else if ($.urlParam("lang") == "hr") {
loadJS("js/lang.hr.js");
$("#lang-hr").css("font-weight", "bolder");
} else {
loadJS("js/lang.sl.js");
$("#lang-sl").css("font-weight", "bolder");
}
function fillIn(key, value) {
document.getElementById(key).innerHTML = value;
}
//Fill in translations
for(var key in lang) {
fillIn(key, lang[key]);
}
});
Additionally to that basic example I added some exceptions to insert language-specific values into some HTML tag attributes.
Such approach works like a charm for about 200 language keys – I have not tested for more. The whole site is served by an RPi and JS loading of language-specific texts is not noticeable on a client.