HOWTO: How to localize a JavaScript application
Using GNU GetText and the LocalePlanet API
Step by Step
- Add the LocalePlanet scripts to your pages:
<script src="http://www.localeplanet.com/api/auto/icu.js"></script>
<script src="http://www.localeplanet.com/api/translate.js"></script>
- Everywhere you display a number or date, use one of the icu.js functions to format it first.
For example, you would change
today.getDay() + '/' + today.getMonth() + '/' + today.getFullYear()
to
icu.getDateFormat('SHORT_CENTURY').format(today)
- Everywhere you display text, pass it to the
_()
function.
For example, you would change
alert('Hello, world!');
to
alert(_('Hello, world!'));
. -
You can use the previous two steps together. For example, you would change
alert('Today is ' + today.getDay() + '/' + today.getMonth() + '/' + today.getFullYear());
to
alert(_("Today is {0}", icu.getDateFormat('SHORT_CENTURY').format(today)));
- Use the GNU gettext programs to extract the text from your pages. You end up with a
.po
file with just the text strings in your native language. - Translate the
.po
file. Most translators/services/etc. can work with them. I recommend poedit, a simple GUI program that works on Windows/Mac/Linux. You will end up with an additional.po
file for each translated language. - Use the po2js or po2json scripts to convert the
.po
files to something usable by JavaScript. Put these files on your website and add the appropriate one to your pages. - Call
_.setTranslation()
with the JSON data from the previous step.
Notes
- You can change the global names. See the icu.js and translate.js script documentation for details.
- You can try gt4po to use Google Translate on your
.po
file, but results are “mixed”, especially for short or unusual strings.