Dynamic Cookie-enabled i18n Localization Plugin - lang-js

File Size: 25.9 KB
Views Total: 1594
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Dynamic Cookie-enabled i18n Localization Plugin - lang-js

lang-js is a simple yet powerful jQuery localization and internationalization plugin which lets you create multi-language international pages with ease.

The plugin enables you to translates strings in the languages you provide in JSON data, and to persist the current language in the cookies.

Basic usage:

1. Include the necessary jQuery and js-cookie libraries on the page.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" 
        integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" 
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>

2. Download the put the jquery-lang.js script after jQuery library.

<script src="js/jquery-lang.js"></script>

3. Create a JSON file containing the translations as these:

// th.json
{
  "token": {
    "Property Search":"ค้นหา",
    "Location":"สถานที่ตั้ง",
    "Min Beds":"จำนวนห้องนอน",
    ...
  },
  "regex": [
    ["Budget", "งบประมาณ"],
    ["^Something at start of text", ""],
    ["This will be case insensitive", "i", ""]
  ]
}

4. Intialize the plugin and specify the default language.

<script src="js/jquery-lang.js"></script>

5. Intialize the plugin and specify the default language.

var lang = new Lang();
lang.init({
  defaultLang: 'en'
});

6. Load the th.json into the document.

lang.dynamic('th', 'th.json');

7. Switch to the TH language.

window.lang.change('th');

8. You can also specify the translations in a JS file:

Lang.prototype.pack.th = {
  "token": {
    "Property Search":"ค้นหา",
    "Location":"สถานที่ตั้ง",
    "Min Beds":"จำนวนห้องนอน",
    ...
  },
  "regex": [
    [/Budget/, "งบประมาณ"],
    [/^Something at start of text/, ""],
    [/This will be case insensitive/i, ""]
  ]
};

9. Possible options to control cookies:

lang.init({

  cookie: {
    // cookie name
    name: 'langCookie',
    //  expiration date
    expiry: 365,
    // path
    path: '/'
  },
   
  // If true, cookies will override the "currentLang" option if the cookie is set.
  allowCookieOverride: true

});

Changelog:

2020-06-12

  • Changed obsolete jQuery Context selector in _translateContent

This awesome jQuery plugin is developed by Irrelon. For more Advanced Usages, please check the demo page or visit the official website.