It's a small library to provide the Rails I18n translations on the JavaScript.
--- Features: - Pluralization - Date/Time localization - Number localization - Locale fallback - Asset pipeline support - Lots more! :) ## Version Notice The `main` branch (including this README) is for latest `3.0.0` instead of `2.x`. ## Usage ### Installation #### Rails app Add the gem to your Gemfile. ```ruby gem "i18n-js" ``` #### Rails with [webpacker](https://github.com/rails/webpacker) If you're using `webpacker`, you may need to add the dependencies to your client with: ``` yarn add i18n-js # or, if you're using npm, npm install i18n-js ``` For more details, see: - [this gist](https://gist.github.com/bazzel/ecdff4718962e57c2d5569cf01d332fe) - https://github.com/fnando/i18n-js/issues/597 #### Rails app with [Asset Pipeline](http://guides.rubyonrails.org/asset_pipeline.html) If you're using the [asset pipeline](http://guides.rubyonrails.org/asset_pipeline.html), then you must add the following line to your `app/assets/javascripts/application.js`. ```javascript // // This is optional (in case you have `I18n is not defined` error) // If you want to put this line, you must put it BEFORE `i18n/translations` //= require i18n // Some people even need to add the extension to make it work, see https://github.com/fnando/i18n-js/issues/283 //= require i18n.js // // This is a must //= require i18n/translations ``` #### Rails app without [Asset Pipeline](http://guides.rubyonrails.org/asset_pipeline.html) First, put this in your `application.html` (layout file). Then get the JS files following the instructions below. ```erb <%# This is just an example, you can put `i18n.js` and `translations.js` anywhere you like %> <%# Unlike the Asset Pipeline example, you need to require both **in order** %> <%= javascript_include_tag "i18n" %> <%= javascript_include_tag "translations", skip_pipeline: true %> ``` **There are two ways to get `translations.js` (For Rails app without Asset Pipeline).** 1. This `translations.js` file can be automatically generated by the `I18n::JS::Middleware`. Just add `config.middleware.use I18n::JS::Middleware` to your `config/application.rb` file. 2. If you can't or prefer not to generate this file, you can move the middleware line to your `config/environments/development.rb` file and run `rake i18n:js:export` before deploying. This will export all translation files, including the custom scopes you may have defined on `config/i18n-js.yml`. If `I18n.available_locales` is set (e.g. in your Rails `config/application.rb` file) then only the specified locales will be exported. Current version of `i18n.js` will also be exported to avoid version mismatching by downloading. #### Export Configuration (For translations) Exported translation files generated by `I18n::JS::Middleware` or `rake i18n:js:export` can be customized with config file `config/i18n-js.yml` (use `rails generate i18n:js:config` to create it). You can even get more files generated to different folders and with different translations to best suit your needs. The config file also affects developers using Asset Pipeline to require translations. Except the option `file`, since all translations are required by adding `//= require i18n/translations`. Examples: ```yaml translations: - file: "public/javascripts/path-to-your-messages-file.js" only: "*.date.formats" - file: "public/javascripts/path-to-your-second-file.js" only: ["*.activerecord", "*.admin.*.title"] ``` If `only` is omitted all the translations will be saved. Also, make sure you add that initial `*`; it specifies that all languages will be exported. If you want to export only one language, you can do something like this: ```yaml translations: - file: "public/javascripts/en.js" only: "en.*" - file: "public/javascripts/pt-BR.js" only: "pt-BR.*" ``` Optionally, you can auto generate a translation file per available locale if you specify the `%{locale}` placeholder. ```yaml translations: - file: "public/javascripts/i18n/%{locale}.js" only: "*" - file: "public/javascripts/frontend/i18n/%{locale}.js" only: ["*.frontend", "*.users.*"] ``` You can also include ERB in your config file. ```yaml translations: <% Widgets.each do |widget| %> - file: <%= "'#{widget.file}'" %> only: <%= "'#{widget.only}'" %> <% end %> ``` You are able to exclude certain phrases or whole groups of phrases by specifying the YAML key(s) in the `except` configuration option. The outputted JS translations file (exported or generated by the middleware) will omit any keys listed in `except` configuration param: ```yaml translations: - except: ["*.active_admin", "*.ransack", "*.activerecord.errors"] ``` #### Export Configuration (For other things) - `I18n::JS.config_file_path` Expected Type: `String` Default: `config/i18n-js.yml` Behaviour: Try to read the config file from that location - `I18n::JS.export_i18n_js_dir_path` Expected Type: `String` Default: `public/javascripts` Behaviour: - Any `String`: considered as a relative path for a folder to `Rails.root` and export `i18n.js` to that folder for `rake i18n:js:export` - Any non-`String` (`nil`, `false`, `:none`, etc): Disable `i18n.js` exporting - `I18n::JS.sort_translation_keys` Expected Type: `Boolean` Default: `true` Behaviour: - Sets whether or not to deep sort all translation keys in order to generate identical output for the same translations - Set to true to ensure identical asset fingerprints for the asset pipeline - You may also set `export_i18n_js` and `sort_translation_keys` in your config file, e.g.: ```yaml export_i18n_js: false # OR export_i18n_js: "my/path" sort_translation_keys: false translations: - ... ``` To find more examples on how to use the configuration file please refer to the tests. #### Fallbacks If you specify the `fallbacks` option, you will be able to fill missing translations with those inside fallback locale(s). Default value is `true`. Examples: ```yaml fallbacks: true translations: - file: "public/javascripts/i18n/%{locale}.js" only: "*" ``` This will enable merging fallbacks into each file. (set to `false` to disable). If you use `I18n` with fallbacks, the fallbacks defined there will be used. Otherwise `I18n.default_locale` will be used. ```yaml fallbacks: :de translations: - file: "public/javascripts/i18n/%{locale}.js" only: "*" ``` Here, the specified locale `:de` will be used as fallback for all locales. ```yaml fallbacks: fr: ["de", "en"] de: "en" translations: - file: "public/javascripts/i18n/%{locale}.js" only: "*" ``` Fallbacks defined will be used, if not defined (e.g. `:pl`) `I18n.fallbacks` or `I18n.default_locale` will be used. ```yaml fallbacks: :default_locale translations: - file: "public/javascripts/i18n/%{locale}.js" only: "*" ``` Setting the option to `:default_locale` will enforce the fallback to use the `I18n.default_locale`, ignoring `I18n.fallbacks`. Examples: ```yaml fallbacks: false translations: - file: "public/javascripts/i18n/%{locale}.js" only: "*" ``` You must disable this feature by setting the option to `false`. To find more examples on how to use the configuration file please refer to the tests. #### Namespace Setting the `namespace` option will change the namespace of the output Javascript file to something other than `I18n`. This can be useful in no-conflict scenarios. Example: ```yaml translations: - file: "public/javascripts/i18n/translations.js" namespace: "MyNamespace" ``` will create: ``` MyNamespace.translations || (MyNamespace.translations = {}); MyNamespace.translations["en"] = { ... } ``` ### Adding prefix & suffix to the translations file(s) Setting the `prefix: "import I18n from 'i18n-js';\n"` option will add the line at the beginning of the resultant translation file. This can be useful to use this gem with the [i18n-js](https://www.npmjs.com/package/i18n-js) npm package, which is quite useful to use it with webpack. The user should provide the semi-colon and the newline character if needed. For example: ```yaml translations: - file: "public/javascripts/i18n/translations.js" prefix: "import I18n from 'i18n-js';\n" ``` will create: ``` import I18n from 'i18n-js'; I18n.translations || (I18n.translations = {}); ``` `suffix` option is added in https://github.com/fnando/i18n-js/pull/561. It's similar to `prefix` so won't explain it in details. #### Pretty Print Set the `pretty_print` option if you would like whitespace and indentation in your output file (default: false) ```yaml translations: - file: "public/javascripts/i18n/translations.js" pretty_print: true ``` #### Javascript Deep Merge (:js_extend option) By default, the output file Javascript will call the `I18n.extend` method to ensure that newly loaded locale files are deep-merged with any locale data already in memory. To disable this either globally or per-file, set the `js_extend` option to false ```yaml js_extend: false # this will disable Javascript I18n.extend globally translations: - file: "public/javascripts/i18n/translations.js" js_extend: false # this will disable Javascript I18n.extend for this file ``` #### Vanilla JavaScript Just add the `i18n.js` file to your page. You'll have to build the translations object by hand or using your favorite programming language. More info below. #### Via NPM with webpack and CommonJS Add the following line to your package.json dependencies where version is the version you want: ```javascript "i18n-js": "{version_constraint}" // Or if you want unreleased version // npm install requires it to be the gzipped tarball, see [npm install](https://www.npmjs.org/doc/cli/npm-install.html) "i18n-js": "https://github.com/fnando/i18n-js/archive/{tag_name_or_branch_name_or_commit_sha}.tar.gz" ``` Run npm install then use via ```javascript var i18n = require("i18n-js"); ``` ### Setting up You **don't** need to set up a thing. The default settings will work just okay. But if you want to split translations into several files or specify contexts, you can follow the rest of this setting up section. Set your locale is easy as ```javascript I18n.defaultLocale = "pt-BR"; I18n.locale = "pt-BR"; I18n.currentLocale(); // pt-BR ``` **NOTE:** You can now apply your configuration **before I18n** is loaded like this: ```javascript I18n = {}; // You must define this object in top namespace, which should be `window` I18n.defaultLocale = "pt-BR"; I18n.locale = "pt-BR"; // Load I18n from `i18n.js`, `application.js` or whatever I18n.currentLocale(); // pt-BR ``` In practice, you'll have something like the following in your `application.html.erb`: ```erb ``` You can use translate your messages: ```javascript I18n.t("some.scoped.translation"); // or translate with explicit setting of locale I18n.t("some.scoped.translation", { locale: "fr" }); ``` You can also interpolate values: ```javascript // You need the `translations` object setup first I18n.translations["en"] = { greeting: "Hello %{name}", }; I18n.t("greeting", { name: "John Doe" }); ``` You can set default values for missing scopes: ```javascript // simple translation I18n.t("some.missing.scope", { defaultValue: "A default message" }); // with interpolation I18n.t("noun", { defaultValue: "I'm a {{noun}}", noun: "Mac" }); ``` You can also provide a list of default fallbacks for missing scopes: ```javascript // As a scope I18n.t("some.missing.scope", { defaults: [{ scope: "some.existing.scope" }] }); // As a simple translation I18n.t("some.missing.scope", { defaults: [{ message: "Some message" }] }); ``` Default values must be provided as an array of hashes where the key is the type of translation desired, a `scope` or a `message`. The translation returned will be either the first scope recognized, or the first message defined. The translation will fallback to the `defaultValue` translation if no scope in `defaults` matches and if no default of type `message` is found. Translation fallback can be enabled by enabling the `I18n.fallbacks` option: ```erb ``` By default missing translations will first be looked for in less specific versions of the requested locale and if that fails by taking them from your `I18n.defaultLocale`. ```javascript // if I18n.defaultLocale = "en" and translation doesn't exist // for I18n.locale = "de-DE" this key will be taken from "de" locale scope // or, if that also doesn't exist, from "en" locale scope I18n.t("some.missing.scope"); ``` Custom fallback rules can also be specified for a particular language. There are three different ways of doing it so: ```javascript I18n.locales.no = ["nb", "en"]; I18n.locales.no = "nb"; I18n.locales.no = function (locale) { return ["nb"]; }; ``` ### Translation Missing Behaviour Control By default a missing translation will be displayed as [missing "name of scope" translation] While you are developing or if you do not want to provide a translation in the default language you can set ```javascript I18n.missingBehaviour = "guess"; ``` this will take the last section of your scope and guess the intended value. Camel case becomes lower cased text and underscores are replaced with space questionnaire.whatIsYourFavorite_ChristmasPresent becomes "what is your favorite Christmas present" #### Option `missingTranslationPrefix` In order to still detect untranslated strings, you can set `I18n.missingTranslationPrefix` to something like: ```javascript I18n.missingTranslationPrefix = "EE: "; ``` And result will be: ```javascript "EE: what is your favorite Christmas present"; ``` This will help you doing automated tests against your localisation assets. #### Customize return when translation entry missing Some people prefer returning `null`/`undefined` for missing translation: ```javascript I18n.missingTranslation = function (scope, options) { return undefined; }; ``` ### Option `defaultSeparator` (global) / `separator` (local) Default separator of translation key is `.` (dot) Meaning `I18n.t("scope.entry")` would search for translation entry `I18n.translations[locale].scope.entry` Using a different separator can be done either globally or locally. Globally: `I18n.defaultSeparator = newSeparator` Locally: `I18n.t("full_sentences|Server Busy. Please retry later", {separator: '|'})` ### Pluralization Pluralization is possible as well and by default provides English rules: ```javascript I18n.t("inbox.counting", { count: 10 }); // You have 10 messages ``` The sample above expects the following translation: ```yaml en: inbox: counting: one: You have 1 new message other: You have {{count}} new messages zero: You have no messages ``` **NOTE:** Rails I18n recognizes the `zero` option. If you need special rules just define them for your language, for example Russian, just add a new pluralizer: ```javascript I18n.pluralization["ru"] = function (count) { var key = count % 10 == 1 && count % 100 != 11 ? "one" : [2, 3, 4].indexOf(count % 10) >= 0 && [12, 13, 14].indexOf(count % 100) < 0 ? "few" : count % 10 == 0 || [5, 6, 7, 8, 9].indexOf(count % 10) >= 0 || [11, 12, 13, 14].indexOf(count % 100) >= 0 ? "many" : "other"; return [key]; }; ``` You can find all rules on