Translation in JavaScript like gettext in PHP?
I generally export the translations in a JavaScript structure:
var app = {};
var app.translations = {
en: {
hello: "Hello, World!",
bye: "Goodbye!"
},
nl: {
hello: "Hallo, Wereld!",
bye: "Tot ziens!"
}
};
The current language of the page texts can be defined using: <html xml:lang="en" lang="nl">
This can be read in JavaScript:
var currentLanguage = document.documentElement.lang || "en";
app.lang = app.translations[ currentLanguage ] || app.translations.en;
And then you can write code like this:
alert( app.lang.hello );
Optionally, a i18n()
or gettext()
function can bring some intelligence, to return the default text if the key does not exist). For example:
function gettext( key )
{
return app.lang[ key ] || app.translations.en[ key ] || "{translation key not found: " + key + "}";
}
Try, jQuery i18n or jQuery localisation
An example for jQuery i18n, and of course you need to generate JSON based dictionary from language file from php
var my_dictionary = {
"some text" : "a translation",
"some more text" : "another translation"
}
$.i18n.setDictionary(my_dictionary);
$('div#example').text($.i18n._('some text'));
JSGettext (archived link) is best implementation of GNU gettext spec. First download JSGETTEXT package and include in your page /js/Gettext.js
<?php
$locale = "ja_JP.utf8";
if(isSet($_GET["locale"]))$locale = $_GET["locale"];
?>
<html>
<head>
<link rel="gettext" type="application/x-po" href="/locale/<?php echo $locale ?>/LC_MESSAGES/messages.po" />
<script type="text/javascript" src="/js/Gettext.js"></script>
<script type="text/javascript" src="/js/test.js"></script>
</head>
<body>
Test!
</body>
</html>
javascript code for example
window.onload = function init(){
var gt = new Gettext({ 'domain' : 'messages' });
alert(gt.gettext('Hello world'));
}
For reference find below link. It's working fine without converting .js file to .php.
Click here
The easiest way is having a PHP file write the translations from gettext
into JavaScript variables.
js_lang.php:
word_hello = "<?php echo gettext("hello"); ?>"
word_world = "<?php echo gettext("world"); ?>"
word_how_are_you = "<?php echo gettext("how_are_you"); ?>"
and then include it:
<script type="text/javascript" src="js_lang.php"></script>
I would also recommend this method in conjunction with the translation plugins S.Mark mentions (which are very interesting!).
You can define the dictionary in the current page's header, too, without including an external file, but that way, you would have to look up and send the data on every page load - quite unnecessary, as a dictionary tends to change very rarely.