Gathering detailed insights and metrics for node-polyglot
Gathering detailed insights and metrics for node-polyglot
Gathering detailed insights and metrics for node-polyglot
Gathering detailed insights and metrics for node-polyglot
@types/node-polyglot
TypeScript definitions for node-polyglot
fastify-i18n
Internationalization plugin for Fastify. Built upon node-polyglot.
node-translate
A translation library for NodeJS that wraps node-polyglot
@entva/react-local
A React internationalization library inspired by node-polyglot
Give your JavaScript the ability to speak many languages.
npm install node-polyglot
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,708 Stars
255 Commits
208 Forks
188 Watching
5 Branches
60 Contributors
Updated on 11 Nov 2024
JavaScript (99.35%)
Makefile (0.65%)
Cumulative downloads
Total Downloads
Last day
10.9%
41,855
Compared to previous day
Last week
8.8%
208,314
Compared to previous week
Last month
15.3%
829,761
Compared to previous month
Last year
-12.6%
8,988,298
Compared to previous year
Polyglot.js is a tiny I18n helper library written in JavaScript, made to work both in the browser and in CommonJS environments (Node). It provides a simple solution for interpolation and pluralization, based off of Airbnb’s experience adding I18n functionality to its Backbone.js and Node apps.
I18n is incredibly important for us at Airbnb, as we have listings in 192 countries, and we translate our site into 30-odd different languages. We’re also hiring talented engineers to help us scale up to meet the challenges of building a global marketplace.
View the documentation on Github.
View the annotated source.
Polyglot is agnostic to your translation backend. It doesn’t perform any translation; it simply gives you a way to manage translated phrases from your client- or server-side JavaScript application.
install with npm:
$ npm install node-polyglot
Clone the repo, run npm install
, and npm test
.
First, create an instance of the Polyglot
class, which you will use for translation.
1var polyglot = new Polyglot();
Polyglot is class-based so you can maintain different sets of phrases at the same time, possibly in different locales. This is very useful for example when serving requests with Express, because each request may have a different locale, and you don’t want concurrent requests to clobber each other’s phrases.
See Options Overview for information about the options object you can choose to pass to new Polyglot
.
Tell Polyglot what to say by simply giving it a phrases object, where the key is the canonical name of the phrase and the value is the already-translated string.
1polyglot.extend({ 2 "hello": "Hello" 3}); 4 5polyglot.t("hello"); 6=> "Hello"
You can also pass a mapping at instantiation, using the key phrases
:
1var polyglot = new Polyglot({phrases: {"hello": "Hello"}});
Polyglot doesn’t do the translation for you. It’s up to you to give it the proper phrases for the user’s locale.
A common pattern is to gather a hash of phrases in your backend, and output
them in a <script>
tag at the bottom of the document. For example, in Rails:
app/controllers/home_controller.rb
1def index 2 @phrases = { 3 "home.login" => I18n.t("home.login"), 4 "home.signup" => I18n.t("home.signup"), 5 ... 6 } 7end
app/views/home/index.html.erb
1<script> 2 var polyglot = new Polyglot({phrases: <%= raw @phrases.to_json %>}); 3</script>
And now you can utilize i.e. polyglot.t("home.login")
in your JavaScript application
or Handlebars templates.
Polyglot.t()
also provides interpolation. Pass an object with key-value pairs of
interpolation arguments as the second parameter.
1polyglot.extend({ 2 "hello_name": "Hola, %{name}." 3}); 4 5polyglot.t("hello_name", {name: "DeNiro"}); 6=> "Hola, DeNiro."
Polyglot also supports nested phrase objects.
1polyglot.extend({ 2 "nav": { 3 "hello": "Hello", 4 "hello_name": "Hello, %{name}", 5 "sidebar": { 6 "welcome": "Welcome" 7 } 8 } 9}); 10 11polyglot.t("nav.sidebar.welcome"); 12=> "Welcome"
The substitution variable syntax is customizable.
1var polyglot = new Polyglot({ 2 phrases: { 3 "hello_name": "Hola {{name}}" 4 }, 5 interpolation: {prefix: '{{', suffix: '}}'} 6}); 7 8polyglot.t("hello_name", {name: "DeNiro"}); 9=> "Hola, DeNiro."
For pluralization to work properly, you need to tell Polyglot what the current locale is. You can use polyglot.locale("fr")
to set the locale to, for example, French. This method is also a getter:
1polyglot.locale() 2=> "fr"
You can also pass this in during instantiation.
1var polyglot = new Polyglot({locale: "fr"});
Currently, the only thing that Polyglot uses this locale setting for is pluralization.
Polyglot provides a very basic pattern for providing pluralization based on a single string that contains all plural forms for a given phrase. Because various languages have different nominal forms for zero, one, and multiple, and because the noun can be before or after the count, we have to be overly explicit about the possible phrases.
To get a pluralized phrase, still use polyglot.t()
but use a specially-formatted phrase string that separates the plural forms by the delimiter ||||
, or four vertical pipe characters.
For pluralizing "car" in English, Polyglot assumes you have a phrase of the form:
1polyglot.extend({ 2 "num_cars": "%{smart_count} car |||| %{smart_count} cars", 3});
Please keep in mind that smart_count
is required. No other option name is taken into account to transform pluralization strings.
In English (and German, Spanish, Italian, and a few others) there are only two plural forms: singular and not-singular.
Some languages get a bit more complicated. In Czech, there are three separate forms: 1, 2 through 4, and 5 and up. Russian is even more involved.
1var polyglot = new Polyglot({locale: "cs"}); // Czech 2polyglot.extend({ 3 "num_foxes": "Mám %{smart_count} lišku |||| Mám %{smart_count} lišky |||| Mám %{smart_count} lišek" 4})
polyglot.t()
will choose the appropriate phrase based on the provided smart_count
option, whose value is a number.
1polyglot.t("num_cars", {smart_count: 0}); 2=> "0 cars" 3 4polyglot.t("num_cars", {smart_count: 1}); 5=> "1 car" 6 7polyglot.t("num_cars", {smart_count: 2}); 8=> "2 cars"
As a shortcut, you can also pass a number to the second parameter:
1polyglot.t("num_cars", 2); 2=> "2 cars"
Polyglot provides some default pluralization rules for some locales. You can specify a different set of rules through the pluralRules
constructor param.
1var polyglot = new Polyglot({ 2 pluralRules: { 3 pluralTypes: { 4 germanLike: function (n) { 5 // is 1 6 if (n === 1) { 7 return 0; 8 } 9 // everything else 10 return 1; 11 }, 12 frenchLike: function (n) { 13 // is 0 or 1 14 if (n <= 1) { 15 return 0; 16 } 17 // everything else 18 return 1; 19 } 20 }, 21 pluralTypeToLanguages: { 22 germanLike: ['de', 'en', 'xh', 'zu'], 23 frenchLike: ['fr', 'hy'] 24 } 25 } 26});
This can be useful to support locales that polyglot does not support by default or to change the rule definitions.
The most-used method. Provide a key, and t()
will return the phrase.
polyglot.t("hello");
=> "Hello"
The phrase value is provided first by a call to polyglot.extend()
or polyglot.replace()
.
Pass in an object as the second argument to perform interpolation.
polyglot.t("hello_name", {name: "Spike"});
=> "Hello, Spike"
Pass a number as the second argument as a shortcut to smart_count
:
1// same as: polyglot.t("car", {smart_count: 2}); 2polyglot.t("car", 2); 3=> "2 cars"
If you like, you can provide a default value in case the phrase is missing. Use the special option key "_" to specify a default.
1polyglot.t("i_like_to_write_in_language", { 2 _: "I like to write in %{language}.", 3 language: "JavaScript" 4}); 5=> "I like to write in JavaScript."
Use extend
to tell Polyglot how to translate a given key.
1polyglot.extend({ 2 "hello": "Hello", 3 "hello_name": "Hello, %{name}" 4});
The key can be any string. Feel free to call extend
multiple times; it will override any phrases with the same key, but leave existing phrases untouched.
Use unset
to selectively remove keys from a polyglot instance.
unset
accepts one argument: either a single string key, or an object whose keys are string keys, and whose values are ignored unless they are nested objects (in the same format).
Example:
1polyglot.unset('some_key'); 2polyglot.unset({ 3 hello: 'Hello', 4 hello_name: 'Hello, %{name}', 5 foo: { 6 bar: 'This phrase’s key is "foo.bar"' 7 } 8});
Get or set the locale (also can be set using the constructor option, which is used only for pluralization. If a truthy value is provided, it will set the locale. Afterwards, it will return it.
Clears all phrases. Useful for special cases, such as freeing up memory if you have lots of phrases but no longer need to perform any translation. Also used internally by replace
.
Completely replace the existing phrases with a new set of phrases.
Normally, just use extend
to add more phrases, but under certain circumstances, you may want to make sure no old phrases are lying around.
Returns true
if the key does exist in the provided phrases, otherwise it will return false
.
Takes a phrase string and transforms it by choosing the correct plural form and interpolating it. This method is used internally by t.
The correct plural form is selected if substitutions.smart_count is set.
You can pass in a number instead of an Object as substitutions
as a shortcut for smart_count
.
You should pass in a third argument, the locale, to specify the correct plural type. It defaults to 'en'
which has 2 plural forms.
new Polyglot
accepts a number of options:
phrases
: a key/value map of translated phrases. See Translation.locale
: a string describing the locale (language and region) of the translation, to apply pluralization rules. see PluralizationallowMissing
: a boolean to control whether missing keys in a t
call are allowed. If false
, by default, a missing key is returned and a warning is issued.onMissingKey
: if allowMissing
is true
, and this option is a function, then it will be called instead of the default functionality. Arguments passed to it are key
, options
, and locale
. The return of this function will be used as a translation fallback when polyglot.t('missing.key')
is called (hint: return the key).interpolation
: an object to change the substitution syntax for interpolation by setting the prefix
and suffix
fields.pluralRules
: an object of pluralTypes
and pluralTypeToLanguages
to control pluralization logic.No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 10/15 approved changesets -- score normalized to 6
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More