Translate Strings In Any Elements & Attributes – simple-translator

Category: Javascript , Text | December 20, 2021
Author:andreasremdt
Views Total:586 views
Official Page:Go to website
Last Update:December 20, 2021
License:MIT

Preview:

Translate Strings In Any Elements & Attributes – simple-translator

Description:

A simple lightweight translation library written in vanilla JavaScript to translate any strings within the document in the language you specify.

More Features:

  • Persists the current language using local storage.
  • Allows you to translate any HTML attributes such as title, placeholder, src, etc.

Install & Download:

# Yarn
$ yarn add @andreasremdt/simple-translator
# NPM
$ npm i @andreasremdt/simple-translator --save

How to use it:

1. Import the simple-translator library.

// ES Module
import Translator from '@andreasremdt/simple-translator';
// Or from a CDN
<script src="https://unpkg.com/@andreasremdt/simple-translator@latest/dist/umd/translator.min.js" defer
></script>

2. Define translations (key/value pairs) in JSON files and place them into the i18n folder.

// en.json
{
  "title": "Title",
  "content": "Content"
  ...
}

3. Add the data-i18n attribute to the element you want to have multiple languages as follows:

<h1 data-i18n="title">Title</h1>
<h1 data-i18n="content">Content</h1>

4. It also allows you to translate values in any attribute:

<div data-i18n=".label"
     data-i18n-attr="title"
     title="to be translated...">
     Title
</div>

5. Initialize the library.

var translator = new Translator({
    // options here
});
translator.fetch(['en']).then(() => {
  translator.translatePageTo('en');
});

6. Switch between languages.

translator.load("en");
translator.load("de");

7. Translate strings in a custom HTML attribute:

<div
  data-i18n="title"
  data-i18n-attr="title"
  title="Title..."
>
  ...
</div>

8. Determine whether to store the last selected language in the local storage. Default: false.

var translator = new Translator({
    persist: true,
    persistKey: 'preferred_language'
});

9. Specify the file path where the JSON files are located.

var translator = new Translator({
    filesLocation: "/i18n"
});

10. Determine the default language. Default: empty.

var translator = new Translator({
    defaultLanguage: "de"
});

11. Auto determines the user’s desired language.

var translator = new Translator({
    detectLanguage: true
});

12. Override the default selector.

var translator = new Translator({
    selector: '[data-i18n]'
});

13. Determine whether to register the helper globally. When set to a String, it will create a global helper with the same name. When set to false, it won’t register anything.

var translator = new Translator({
    registerGlobally: '__'
});

14. API methods.

// Translates a single translation string into the desired language.
translator.translateForKey(String: key, String?: language);
// Translates all DOM elements that match the selector ('[data-i18n]' by default) into the specified language.
translator.translatePageTo(String?: language);
// Registers a new language to the translator.
translator.add(String: language, Object: translation);
// Removes a registered language from the translator.
translator.remove(String: language);
// Fetches either one or multiple JSON files from your project by utilizing the Fetch API.
translator.fetch(String|Array: languageFiles, Boolean?: save)
// Gets the current language
translator.currentLanguage

Changelog:

v2.0.4 (12/20/2020)

  • Don’t depend on the localStorage API to exist in the environment. Ensures compatibility with Android WebView.

v2.0.3 (09/04/2020)

  • Fixed: The currentLanguage getter now returns the correct language. If language detection is enabled, it will return the detected language by default or otherwise the default language.

v2.0.2 (08/04/2020)

  • feat(translator): convert NodeList into an array

v2.0.0 (07/30/2020)

  • Added a config option registerGlobally that, if specified, registers a global helper with the same name as the given value. This allows you to translate single strings using shortcuts like __(‘header.title’).
  • Added a config option persistKey that specifies the name of the localStorage key.
  • Added a config option debug that, if set to true, prints useful error messages.
  • Added fetch() for easier JSON fetching.
  • Added add() to register new languages to the translator.
  • Added remove() to remove languages from the translator.
  • Added translateForKey() and translatePageTo() to translate single keys or the entire website.
  • Added get currentLanguage to get the currently used language.
  • Transpiled and minified UMD, ESM and CJS builds are available via unpkg and npm.
  • Added a build system for easier packaging and testing.
  • This release is a complete rewrite of the codebase.
  • The methods load() and getTranslationByKey() have been removed in favor of a new API. Use fetch(), translateForKey(), and translatePageTo() instead.
  • The config option languages has been removed.

v1.2.0 (07/21/2020)

  • data-i18n-attr can now translate multiple attributes by providing a space-separated list.

You Might Be Interested In:


Leave a Reply