gettext
February 3, 2008 - 10:40pm — m0n5t3r
This plugin provides basic gettext support for jQuery apps. It loads JSON data, which can be generated easily from standard gettext .po/.mo files. Why go through the additional hassle of .po files? For a small app that needs i18n, one could write the json directly. However, the main advantages I see to gettext are:
- well known editing tools like KBabel, poEdit, gtranslator, Emacs PO mode, etc.
- translation memory, fuzzy matches and other features that become really helpful when your application is big and you have hundreds of strings
Usage
The plugin expects its input data to be a JSON string like
{"": header, "string": "translation", ...}After getting the server side set up (either as a static file - my choice - or as a web service), the client side is simple:
- add to the head section of the page something like:
<link href="path/to/translation.json" lang="ro" rel="gettext"/> - in your script, use
$.gt.gettext(string)
or
_(string)
for plural forms, use
$.gt.ngettext(sg, pl1[, pl2, ...], count)
or
n_(sg, pl1[, pl2, ...], count) - to extract strings to a
.pofile, you can use standard gettext utilities likexgettextandmsgfmt; to generate the JSON, one could use the following Python snippet, assuming adomain.mofile exists underpath/lang/LC_MESSAGES:
import simplejson as enc
import gettext
def gettext_json(domain, path, lang = [], indent = False):
try:
tr = gettext.translation(domain, path, lang)
# for unknown reasons, instead of having plural entries like
# key: [sg, pl1...]
# tr._catalog has (key, n): pln,
keys = tr._catalog.keys()
keys.sort()
ret = {}
for k in keys:
v = tr._catalog[k]
if type(k) is tuple:
if k[0] not in ret:
ret[k[0]] = []
ret[k[0]].append(v)
else:
ret[k] = v
return enc.dumps(ret, ensure_ascii = False, indent = indent)
except IOError:
return None
Releases
| Official releases | Date | Size | Links | Status | |
|---|---|---|---|---|---|
| 1.0.4 | 2008-Mar-02 | 4.41 KB | Recommended for 1.2.x | ||