Steve
Steve

Reputation: 319

Localization file for JS and PHP

I did some search about localization files, see that we can use .po file or gettext but, is there any tutorial or sample of a unique solution that will work both in javascript and in php.

I want to only maintain one localization file per language that will work with both JS and PHP languages.

Would appreciates if someone can point me to some links or samples...

Upvotes: 3

Views: 2573

Answers (3)

Amir E. Aharoni
Amir E. Aharoni

Reputation: 1318

First, try to avoid gettext if you can. It's popular and stable, but it puts some burden on the translations maintenance: you will need to change the source strings, and when this happens, gettext needs to update all the message keys, and this may mess up the existing translations. An approach with constant message keys is much easier to maintain in the long run - you will need to remember to delete the keys you don't use any more, but it's a very small burden.

You can use the same translations storage format for PHP and JavaScript. If you use a key-based approach, as I suggest, it will probably be some JSON-based format. JSON is easily accessible in both PHP and JavaScript.

There are several ready-made JavaScript libraries for JSON-based internationalization. I happen to be a developer of one such library: https://github.com/wikimedia/jquery.i18n . It should be reasonably easy to adapt it to PHP.

Upvotes: 3

arkascha
arkascha

Reputation: 42935

I found that it is typically a sign of a questionable design when translatable text is coded inside JS functions. JS is meant to implement logic, not content. The content should be provided by PHP (typically by using a templating engine) and should be used by JS. That way you only need a localization solution for PHP.

If (exceptions always occur) you really need to translate a phrase inside a JS routine you use an ajax call to fetch the translation. This also simplifies the access to the dictionary holding the translation tokens since it is again done by PHP. The dictionary can be kept in a single place.

Upvotes: 3

David Müller
David Müller

Reputation: 5351

Yep, there is. I've successfully used gettext.js a while ago, which is operating on .json or .po files. This way, you only have to maintain one translation source. The webpage I've used this for is located here so you can check out how I've did it. Good luck!

Upvotes: 3

Related Questions