si18n.js

v1.4.4

A simple and lightweight way to integrate internationalization on a small website project.

Changelog

Good morning

This is an example.

Cette phrase n'est pas disponible en anglais.

There is one monkey in the tree.
There are 12 monkeys in the tree.


Current language : en
All available languages : fr, en


# Table of content
# Installation
npm
npm i si18n.js
yarn add si18n.js
CDN ES6 Modules
You can also use si18n.js from a CDN. There are different versions of links available for different CDN platforms. You can pick and use only one link at once.
<!-- si18n.js latest version @1.4.4 -->
<script type="module" src="https://si18n.js.bruxelles.dev/si18n.js"></script>
<script type="module" src="https://si18n.js.bruxelles.dev/si18n.min.js"></script>

<!-- UNPKG -->
<script type="module" src="https://unpkg.com/si18n.js"></script>
<script type="module" src="https://unpkg.com/si18n.js@1.4.4/si18n.js"></script>
<script type="module" src="https://unpkg.com/si18n.js@1.4.4/si18n.min.js"></script>

<!-- jsDelivr -->
<script type="module" src="https://cdn.jsdelivr.net/npm/si18n.js"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/si18n.js@1.4.4"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/si18n.js@1.4.4/si18n.js"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/si18n.js@1.4.4/si18n.min.js"></script>

<!-- ESM -->
<!-- (?target=es2015|es2022|esnext) -->
<script type="module" src="https://esm.sh/si18n.js@1.4.4"></script>

<script type="module" src="https://cdn.jsdelivr.net/npm/si18n.js@1.4.4/+esm"></script>

<!-- UNPKG -->
<script type="module">
  import Si18n from "https://cdn.jsdelivr.net/npm/si18n.js@1.4.4/si18n.min.js";
  // ...
</script>
# Usage
NPM
import Si18n from "si18n";
Basic example
let loc = new Si18n();
loc.init({
  locales: {}, // { "en": {...}, "fr": {...}}
  lang: "fr",
  fallbackLang: "en",
  translate() {
    document.querySelector(".lang").innerText = loc.getLocale();
    document.querySelector(".title").innerText = loc.t("nested.title");
    // ...
  },
  onLocaleChanged() {
    // ...
  }
});
Automatic detection
This allows si18n.js to automatically detect and update the text for the element:
<div data-si18n="site.title"></div>
Not for tag content
When there is the data-si18n-default attribute, and it is set to false, the text will not be set as the content of the tag. You should only use this option for the content of the attributes, without forgetting to mention which attribute(s) they are.
<div data-si18n="site.title" data-si18n-default="false" data-si18n-title="true"></div>
All attributes are:

The following attributes are booleans. They are mandatory depending on the needs. Possible values are true or false.

  • data-si18n-default: If set to false, the text will not be placed in the tag. (Reserved for attributes.)
  • data-si18n-html: If set to true, text will be added as HTML code. Default: false.
  • data-si18n-value for the value attribute of a tag like option and input.
  • data-si18n-alt for the alt attribute of the img tag to provide a text description of the image.
  • data-si18n-title for the title attribute of the tag.
  • data-si18n-label for the label attribute of a tag like optgroup.
  • data-si18n-aria-label for the aria-label attribute of the tag.
  • data-si18n-placeholder for the placeholder attribute of the input and textarea tags.
  • data-si18n-content for the attribute content of a tag like meta for the description of the page, for example (useful if you use Prerendering technology.
The lang and dir attributes of the html tag are set automatically. The only thing you can do for the dir attribute is to set it manually for all languages or only for rtl (boolean) languages. Default: ltr. e.g.: "rtl": true.
Replacement of values
Besides doing simple text replacements, si18n.js can also insert values into placeholders for that purpose. Just define a key-value in the argument values (second argument) of the method t. And in your texts, all you have to do is reserve the spaces with a %{X} where X is the key (number or property name) of the value to insert. Example:
<!-- 1. HTML -->
<p id="intro"></p>
// 2. JAVASCRIPT
// 2.1.
let data = {
  "fr": {
    "intro": "%{name} a eu %{age} ans cette année.",
    "test": "Ceci est un test."
  },
  "en": {
    "intro": "%{name} turned %{age} this year.",
    "test": "This is a test."
  }
};

loc.init({
  // ...
  translate() {
    document.querySelector("#intro").innerText = loc.t("intro", {
      age: (new Date().getFullYear()) - birthYear,
      name: "John Doe"
    });

    console.log(loc.t("test")) // "Ceci est un test."
    // ...
  }
});
or
// 2.2.
let data = {
  "fr": { "intro": "Mon ami s'appelle %{0} et travaille chez %{1}." },
  "en": { "intro": "My friend's name is %{0} and he works at %{1}." }
};

loc.init({
  // ...
  translate() {
    document.querySelector("#intro").innerText = loc.t("intro", {
      0: "Georges",
      1: "CRFEV"
    });
    // ...
  }
});
# Methods (7)
Method Argument Description
constructor options:object Does the same thing as the following init method.
init options:object Recommanded - Initializes the si18n object with the given options.
setLocale lang:string Sets the given language and applies the change by calling the translate option method. Don't use this method if have configured the togglersSelector option.
getLocale void Returns the current language code (e.g.: 'en').
getLocales void Returns the list of all available languages (e.g.: ['fr', 'en', 'it']).
t JSONPath:string,
values:object
Returns the translation string at the given key (e.g.: heroTitle, site.title, site.menu.link1).
The values argument is optional. If provided, it must contain the key-values to be replaced. See the example below.
static async getJSON URL: string,
callback(res: object): fn
Retrieves and returns the data from the given URL in JSON format in the callback function parameter.
toJSON void Returns the options of the instance.
# Default options (11)
Argument Default value Description
locales {} Object containing your language translations. Required only if path is not defined.
path null Absolute access path to the directory containing your translation files. The files will be loaded automatically according to the active language (the fallback language will always be loaded). Priority over the locales option. Required only if locales is not defined. e.g.: ./locales.
availableLocales [] List containing the names of available languages as defined in the translation files. Required only if path is defined.
lang '' Active language to use. Don't use it if you want to let the browser's language detector provide the language. If this option is not set, the fallbackLang option becomes required.
fallbackLang '' Fallback language. The language to use when the requested language or a requested string in a non-fully translated language is missing. If not set, the fallback language will be the current one.
activeClass '' Class to add to the active button for the current language. Use only if togglersSelector is used.
togglersSelector '' CSS selector for toggler elements. si18n.js will add a click event to selected items. Do not set this option if you are using the setLocale(lang) method. These elements must compulsorily have the attribute data-lang="XX" where XX corresponds to the language code of the button (toggler element) to be detected.
isTogglerSelect false Whether the toggler is a select or button element (or whatever).
saveLang true Whether to save the language in the localStorage.
saveAs 'lang' Name of the key to save the language in the localStorage. If set, the value will be used as key to retrieve the language from the URL parameter (Default: lang).
reloadPage false If this option is set to true, the page will automatically refresh after changing the language. It may only be useful if you have a complex page structure and want the translations to be loaded every time you change the language, to keep it simple.
translate function() {} (required) - Function that translates text manually. For translation use only.
Note: The html tag automatically has a lang attribute with the current language, no need to encode it manually.
onLocaleChanged function() {} Callback function triggered when the language changes. Everything you want to do else because the language has changed, do it here.
By José
dBruxelles