Translate Webpage Using JSON And Data Attributes - lwcTranslator

Translate Webpage Using JSON And Data Attributes - lwcTranslator
File Size: 23.3 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A fast and easy-to-use jQuery client-side translator plugin to internationalize any text and attributes of HTML elements using JSON and HTML data attributes.

How to use it:

1. To get started, include the translator's JavaScript after jQuery library.

<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/lwcTranslator.min.js"></script>

2. Add the data-translation and data-translation-attr attributes to HTML element to be translated.

<html data-translation="lang" data-translation-attr="lang">
  <head>
    <title data-translation="title"></title>
  </head>
  <body>
    <h1 data-translation="header.title"></h1>
    ...
  </body>
</html>

3. Specify the languages in the languages.json.

// languages.json
[
  {
    "name": "English",
    "filename": "en-UK"
  },
  {
    "name": "Deutsch",
    "filename": "de-DE"
  }
]

4. Create localization files as follows:

// en-UK.json
{
  "lang": "en",
  "title": "Page Title",
  "header": {
    "title": "Heading"
  }
}

// de-DE.json
{
  "lang": "de",
  "title": "Mein wundervoller Titel",
  "header": {
    "title": "Hallo Welt!"
  }
}

5. Initialize the plugin and specify the path to the language files. Done.

$('html').lwcTranslator({
  languageSettingsFile: '/path/to/languages.json',
  languageFolderPath: '/path/to/languages/folder/'
});

6. Override the default data attributes:

$('html').lwcTranslator({
  attributes: {
    textTranslation: 'data-translation',
    attrTranslation: 'data-translation-attr'
  }
});

7. Set the default language:

$('html').lwcTranslator({
  defaultLanguage: 'en-UK'
});

8. Enable/disable asynchronous loading.

$('html').lwcTranslator({
  async: true
});

9. Determine whether to support line breaks in the paragraphs.

$('html').lwcTranslator({
  paragraphSupport: true
});

10. Remember the language selection using HTML5 local storage.

if (!window.localStorage['defaultLanguage'])
window.localStorage['defaultLanguage'] = 'en-UK';

$('html').lwcTranslator({
  defaultLanguage: window.localStorage['defaultLanguage'],
});

11. Callback functions.

$('html').lwcTranslator({
  onLanguageSettingsLoaded: function(settings)
    // do something
  },
  onLanguageLoaded: function(language) 
    // do something
  },
  onLanguagesLoaded: function(languages)
    // do something
  }
});

Changelog:

2019-05-05

  • update language translation

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