• Stars
    star
    139
  • Rank 254,694 (Top 6 %)
  • Language
    JavaScript
  • Created over 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

gettext.js is a lightweight yet complete and accurate GNU gettext port for node and the browser.

gettext.js npm version

gettext.js is a lightweight (3kB minified!) but complete and accurate GNU gettext port for Node.js and the browser. Manage your i18n translations the right way in your JavaScript projects.

Why another i18n JavaScript library?

Our aim is to port the famous GNU gettext and ngettext functions to JavaScript, Node.js and browser applications.

gettext.js should respect existing standards, and be lightweight, so:

  • no dictionary loading management
  • no extra features

The end-result is a tiny library (less than 200 lines of JavaScript) that implements the gettext() and ngettext() functions. We have light JSON translation files: we only embed translated forms, and not much headers.

There are good i18n libraries, like Jed and i18n-next. But they are too complex and too heavy, or they do not fully embrace the gettext API and philosophy.

There's also the Orange-OpenSource/gettext.js package, which is pretty good, we were inspired by that project. But that project has not been active since 2012 and doesn't have any tests.

Installation

Debian 9, codename Stretch

apt-get install libjs-gettext.js

Node.js

  1. Install the library with this command: npm install gettext.js --save
  2. Require it in your project:
    var i18n = require("gettext.js")();
    i18n.gettext("foo");

Third-party TypeScript definitions

For TypeScript definitions, use the third-party @types/gettext.js module.

Browser

Get the archive

Download the latest archive.

Get it with Bower

  1. bower install gettext.js --save
<script src="/path/to/dist/gettext.iife.js" type="text/javascript"></script>
<script>
  var i18n = window.i18n(options);
  i18n.gettext("foo");
</script>

Alternatives to IFFE version

As well as the IIFE (Immediately Invoked Function Expression) version, we also have releases for:

  • CommonJS for Node.js
  • AMD
  • ESM

Using a npm CDN

Instead of downloading gettext.js, you may use a npm CDN like unpkg or jsDelivr.

Usage

Load your messages

You can load your messages like this:

// i18n.setMessages(domain, locale, messages, plural_form);
i18n.setMessages(
  "messages",
  "fr",
  {
    Welcome: "Bienvenue",
    "There is %1 apple": ["Il y a %1 pomme", "Il y a %1 pommes"],
  },
  "nplurals=2; plural=n>1;"
);

Or:

// i18n.loadJSON(jsonData /*, domain */);
var json = {
  "": {
    language: "fr",
    "plural-forms": "nplurals=2; plural=n>1;",
  },
  Welcome: "Bienvenue",
  "There is %1 apple": ["Il y a %1 pomme", "Il y a %1 pommes"],
};
i18n.loadJSON(json, "messages");

Read the Required JSON format section below for more info.

Set the locale

In the DOM

You can set your locale in the DOM, like this:

<html lang="fr"></html>

With JavaScript

Or use JavaScript:

i18n.setLocale("fr");

Gettext functions

Name Description Shorthand
gettext(msgid) Translate a string. __()
ngettext(msgid, msgid_plural, n) Translate a pluralizable string. _n()
pgettext(msgctxt, msgid) Translate a string specified by context. _p()
dcnpgettext(domain, msgctxt, msgid, msgid_plural, n) Translate a potentially pluralizable string, potentially specified by context, and potentially of a different domain (as specified in setMessages or loadJSON). None.

Plural forms

ngettext and dcnpgettext accept a n parameter to specify the plural form.

i18n.ngettext('There is an apple', 'There are many apples', 1); // There is an apple
i18n.ngettext('There is an apple', 'There are many apples', 10); // There are many apples
i18n.ngettext('There is %1 apple', 'There are %1 apples', 10); // There are %1 apples
i18n.ngettext('There is %1 apple', 'There are %1 apples', 10, 10); // There are 10 apples

Variabilized strings

All four functions above can take extra arguments for variablization.

gettext('There are %1 in the %2', 'apples', 'bowl'); -> "There are apples in the bowl

ngettext('One %2', '%1 %2', 10, 10, 'bananas'); -> "10 bananas"

It uses the public method i18n.strfmt("string", var1, var2, ...) which you may re-use elsewhere in your project.

Literal percent sign (%)

When you need to have literal percent sign followed by a number (common in Hebrew or Turkish) you can escape it using another percent sign, for example:

gettext('My credit card has an interest rate of %%%1', 20); -> "My credit card has an interest rate of %20"

Or without variables:

gettext('My credit card has an interest rate of %%20'); -> "My credit card has an interest rate of %20"

Required JSON format

You'll find in /bin a po2json.js converter, based on the excellent po2json project that will dump your .po files into the proper JSON format below:

{
  "": {
    "language": "en",
    "plural-forms": "nplurals=2; plural=(n!=1);"
  },
  "simple key": "It's tranlation",
  "another with %1 parameter": "It's %1 tranlsation",
  "a key with plural": [
    "a plural form",
    "another plural form",
    "could have up to 6 forms with some languages"
  ],
  "a context\u0004a contextualized key": "translation here"
}

Pretty formatting

Use bin/po2json.js input.po output.json or bin/po2json.js input.po output.json -p for pretty format.

Parsers

You may use the xgettext-php parser to parse your files. It has helpful JavaScript and Handlebars parsers.

License

MIT

More Repositories

1

Parsley.js

Validate your forms, frontend, without writing a single line of javascript
JavaScript
9,051
star
2

Garlic.js

Automatically persist your forms' text and select field values locally, until the form is submitted.
CSS
2,369
star
3

validator.js

Powerful objects and strings validation in javascript for Node and the browser
JavaScript
255
star
4

Employness

Side-project: let your employees rate their day, and measure their daily satisfaction at work!
PHP
33
star
5

PdfXtractor

Convert PDFs to JPEG images like a charm!
PHP
16
star
6

BalloonNotes

Backbonejs with dualStorage (localStorage + remoteStorage) POC
JavaScript
12
star
7

copacabana

Quick prototyping node+redis+socket.io API RESTPush server for your javascript applications
JavaScript
8
star
8

uwidget

Universal Widget, easily display a API-distant collection of objects, with simple sorting and filters option.
JavaScript
6
star
9

GithubApi_v3

Very simple class I use for my pet projects
PHP
5
star
10

SfTranslationManagement

Find all your translation keys across your project, compare them to your message.yml file and see what's missing and/or what's not used anymore :)
Shell
4
star
11

SilexSocle

Another Silex Boilerplate
PHP
4
star
12

dotfiles

My personal dotfiles
Shell
3
star
13

GithubRandomCodeReview

Very early pet project: Every 5 commits, randomly ask to a team member to quickly review it!
PHP
3
star
14

quantik

Web version of GIGAMIC Quantik board game, with alpha pruning minmax IA
JavaScript
3
star
15

docker-config

My personal docker config
2
star
16

pipewatch

watch your pipe!
JavaScript
2
star
17

react-bootstrap-app

Simple personal React bootstrapped app (redux,saga,i18n,tapestry)
JavaScript
2
star
18

wisemimes

JavaScript
2
star
19

vcr-proxy

A recording/replaying proxy for your SPA functional tests
JavaScript
2
star
20

cryptofriendly

List of websites/e-commerce allowing payments with crypto coins
HTML
2
star
21

meeting-calculator

JavaScript
2
star
22

carolineetguillaume

Site du mariage
JavaScript
2
star
23

interactivity-map

JavaScript
1
star
24

covid19

Basic SIR epidemic model to evaluate the effect of confinement and covid-19
JavaScript
1
star
25

presidentielle2017

1
star
26

wisembly-test-inte

1
star