Translation in JavaScript like gettext in PHP?

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="https://stackoverflow.com/questions/2400106/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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)