Translation in JavaScript like gettext in PHP?

ParisNakitaKejser picture ParisNakitaKejser · Mar 8, 2010 · Viewed 30.6k times · Source

I am using gettext in my PHP code, but I have a big problem. All my JavaScript files are not affected by the translation, can somebody tell me an easy way to get the translations in the chosen language into JavaScript as well.

Answer

Pekka picture Pekka · Mar 8, 2010

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.