I found myself in need of a really simple implementation of I18n in JavaScript, but without a ton of overhead because the use case was pretty straightforward. I really just want to be able to do this in my form handlers:
1return i18n.forms.numberPatternMismatch;
So, I decided to extract the language from the HTML element (since I set it appropriately in the backend using I18n) and set up localization files in JavaScript that I could then reference.
1//= require locales/en.js
2//= require locales/es.js
3/*
4 * Set a global variable `i18n` that contains the current localization strings.
5 * Locale files create simple objects, we just map it in based on the 'lang' attribute
6 * of the HTML node.
7 */
8(function(window, undefined) {
9 var currentLocale = window.document.documentElement.lang,
10 generalLocale = currentLocale.split('-')[0],
11 fallbackLocale = 'en';
12
13 window.i18n = (function(locales) {
14 if (generalLocale in locales) {
15 return locales[generalLocale];
16 } else {
17 return locales[fallbackLocale];
18 }
19 })(window.locales);
20})(window);
And my “locale” file for English:
1/*
2 * English language translations for use in JavaScript.
3 */
4(function(window, undefined) {
5 if (window.locales === undefined) {
6 window.locales = {};
7 }
8
9 window.locales.en = {
10 forms: {
11 /* Form validation messages. */
12 checkboxValueMissing: "Please check the required box.",
13 emailFormat: "Please enter a valid email address.",
14 numberPatternMismatch: "Please only enter numbers.",
15 patternMismatch: "Please only enter numbers.",
16 phone: "Please enter a valid phone number.",
17 selectValueMissing: "Please select an option from the list.",
18 valueMissing: "Please fill out this field.",
19 amountRangeOutOfBounds: function(min, max) {
20 return "Please input a load amount between $" + min + " and $" + max + ".";
21 },
22
23 /* Form submission messages. */
24 cancelText: "Nevermind",
25 confirmText: "I'm Sure",
26 workingValue: "Working…",
27 }
28 };
29})(window);
Simple enough, right?!