jQuery: The Write Less, Do More JavaScript Library

gettext

Average rating
(7 votes)

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 .po file, you can use standard gettext utilities like xgettext and msgfmt; to generate the JSON, one could use the following Python snippet, assuming a domain.mo file exists under path/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 releasesDateSizeLinksStatus
1.0.42008-Mar-024.41 KBRecommended for 1.2.xThis is currently the recommended release for 1.2.x.