Gettext translator
Javascript gettext translations replacement to use with gettext/gettext. Use gettext/json to generate the json data.
Installation
npm install gettext-translator
Usage
Use the Json generator gettext/json library to export the translations to json:
use Gettext\Loader\PoLoader;
use Gettext\Generator\JsonGenerator;
$translations = (new PoLoader())->loadFile('locales/gl.po');
(new JsonGenerator())->generateFile('locales/gl.json');
Load the json file in your browser
import Translator from 'gettext-translator';
async function getTranslator() {
const response = await fetch('locales/gl.json');
const translations = await response.json();
return new Translator(translations);
}
const t = await getTranslator();
t.gettext('hello world');
Variables
You can add variables to the translations. For example:
t.gettext('hello :who', {':who': 'world'});
There's also a basic support o sprintf (only %s
and %d
)
t.gettext('hello %s', 'world');
To customize the translator formatter, just override the format
method:
t.format = function (text, ...args) {
}
Short names
Like in the php version, there are the __
functions that are alias of the long version:
t.gettext('Foo');
t.__('Foo');
API
Long name | Short name | Description |
---|
gettext | __ | Returns a translation |
ngettext | n__ | Returns a translation with singular/plural variations |
dngettext | dn__ | Returns a translation with domain and singular/plural variations |
npgettext | np__ | Returns a translation with context and singular/plural variations |
pgettext | p__ | Returns a translation with a specific context |
dgettext | d__ | Returns a translation with a specific domain |
dpgettext | dp__ | Returns a translation with a specific domain and context |
dnpgettext | dnp__ | Returns a translation with a specific domain, context and singular/plural variations |