Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translation in JavaScript like gettext in PHP?

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.

like image 675
ParisNakitaKejser Avatar asked Mar 08 '10 08:03

ParisNakitaKejser


People also ask

Can PHP use gettext?

The gettext module in PHP only supports languages and language identifiers that are installed on your server. on the command line of your server (e.g., by logging in with SSH). The command may require admin privileges and maybe not work on a hosted shared server.

What is PHP gettext?

October 28, 2020 · 16 min read. GNU gettext is a package that offers to programmers, translators and even users a well integrated set of tools that provide a framework within which other free packages may produce multi-lingual messages.

What is translator in JavaScript?

Translator.js is a JavaScript library built top on Google Speech-Recognition & Translation API to transcript and translate voice and text. It supports many locales and brings globalization in WebRTC!

Is gettext a function?

The gettext function searches the currently selected message catalogs for a string which is equal to msgid . If there is such a string available it is returned.


1 Answers

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.

like image 89
Pekka Avatar answered Sep 23 '22 06:09

Pekka