Translate Strings In Any Elements & Attributes – simple-translator

Category: Javascript , Text | May 23, 2020
Author: andreasremdt
Views Total: 19
Official Page: Go to website
Last Update: May 23, 2020
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.

How to use it:

1. Download the package and import the library as a module.

import Translator from "./translator.js";

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. Initialize the library.

var translator = new Translator({
    languages: ["en", "de"],
});

5. Switch between languages.

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

6. Translate strings in a custom HTML attribute:

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

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

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

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

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

9. Determine the default language. Default: empty.

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

10. Auto determines the user’s desired language.

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

You Might Be Interested In:


Leave a Reply