#4559 closed enhancement (wontfix)
Slightly different approach to javascript localization
Reported by: | nbachiyski | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | |
Component: | I18N | Keywords: | js i18n needs-patch |
Focuses: | Cc: |
Description
Although we now have very nice js localization from Michael Adams in [4968], but there are some things that can be improved, more specifically:
- All the strings for translations have to be extracted from the js source, they have to be give names and have to stay in en external php file
- There is not support for plural forms
- The template strings are processed manually (
message = obj.delText.replace(/%thing%/g, what);
) (this one is not very big problem).
So, I thought, isn't there a way to incorporate gettext into javascript. And after that, I wrote some stupid js gettext implementation. Here is what it looks like:
- A js file can be xgettext-ed using the perl parser, they look almost the same, regarding the strings:
xgettext -L perl <js files>
- The translations are taken from a jsvascript dictionary, which must be given on object initialization. I wrote a simple function to generate this from a mo file. So we can take extract the strings from js files into a separate mo and give them to the jsgettext on load.
- There is a simple format function, which can make things like:
gettext.format("Here are {count} of {type} dragons!", {count: 8, type: 'mighty'});
orgettext.format("Gimme a {0}, a {1} and a {2}", ['ball', 'gun', 'kite']);
- There is the usual gettext plural support. The different plural forms are given as a javascript function (we practically have this, because we generate a php function, which does the same thing)
No more words, here is some code:
// the key for plural forms is singular\0plural (like in the mo file) var trans = { baba: 'dyado', '{0} baba\0{0} babas': ['{0} dyado', '{0} dyados'] }; var l10n = new gettext(trans); alert(l10n.gettext("baba")); alert(gettext.format(l10n.ngettext("{0} baba", "{0} babas", 1), [1]); alert(gettext.format(l10n.ngettext("{0} baba", "{0} babas", 5), [5]);
Eventually, if you have reached this point and you are not totally bored, you can see the code:
- The attached archive is a current (rev23) snapshot of the repository at: http://ncb.googlecode.com/svn/js/gettext/
- In the
app
sub-folder there is a proof-of-concept simple i18n-ed application, which is ready for execution, just open app.php in your browser - You can find some junit unit tests in
test.html
What do you think?
Attachments (4)
Change History (11)
#4
@
17 years ago
- Milestone changed from 2.5 to 2.6
I suspect this doesn't apply to trunk at all anymore.
Pushing to 2.6 for now.
#5
@
15 years ago
- Keywords needs-patch added; has-patch early removed
- Milestone changed from 2.9 to Future Release
Note: See
TracTickets for help on using
tickets.
In order to use it:
js-i18n.diff
.gettext.js
inwp-includes/js/
.jsgettext.php
inwp-includes/
.