📜 ⬆️ ⬇️

po.js is a super simple utility for i18n

When I develop systems on the Zend Framework, I always use gettext and Zend_Translate. Everything is succinctly simple and usually there are no problems with the translation of even large projects. For each language, their own .po and .mo files are generated, the translations dance from the default language, the keys are also in the same language. It is convenient for translators to transfer these files, which they can open in POEdit and conveniently translate everything. So, on the server side, everything is very simple, but often you need to translate some messages “on the fly” into JavaScript, but it does not understand your .mo files. But I would like to use them in order not to divide the translation of one project into 2 parts (backend, frontend). And I started looking. There are quite a few such solutions on the Internet, but for some reason they all become overgrown with dependencies:

code.google.com/p/gettext-js (Prototype)
angular-gettext.rocketeer.be (Angular)
github.com/jakob-stoeck/jquery-gettext (jQuery)

But I wanted to have a “pure-js” solution. Ok, let's write our own.

The first thing I was looking for was how to read the PO files in JS. You can parse, but this is an extra load, so I decided not to force JavaScript and give it ready-made JSON. Therefore, the first thing we have to do is convert PO to JSON. I advise you to use this converter .
')
Next, the algorithm is simple, we save a JSON file to our server, and pass a link to it to pojs. Of course, having connected po.min.js to this page.

<script src="po.min.js"></script> <script> pojs.init('/ru.json'); </script> 


If the current language is default, then you do not need to send a link to JSON.

All transfers are returned after calling the function with the transfer of the key to it. If the key is not found, the key itself will be returned.

 pojs._('Hello world'); 


Also in po.js there is another super-mini feature, a bit similar to sprintf.

 pojs._('My name is %s, and I am %s years old', ['Sasha', 24]); 


If JSON is not cached, it will be received asynchronously, which means that we will not be able to use pojs ._ () immediately after initialization. Wrap the code where translations are used:

 pojs.ready(function() { pojs._('Hello world'); }); 


It is worth noting some advantages of po.js, otherwise there would be no point in doing all this:

1. Nano-size: ~ 0.7KB
2. Does not need third-party dependencies, such as jQuery, Prototype, Angular ...
3. JSON is cached in localStorage. So be careful if you have very large translation files. You can reset the cache simply by adding "? 1" to the link to the JSON file (yes, this is the old school)

po.js on github

ps
I wrote purely for my needs, maybe something is missing for you or something is working wrong. Ready to rule, improve!

Source: https://habr.com/ru/post/229495/


All Articles