• Stars
    star
    139
  • Rank 262,954 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Provides a very basic HTML multilingual support using JavaScript

dom-i18n

NPM version Build Status Code coverage

Provides a very basic HTML multilingual support using JavaScript

http://ruyadorno.github.io/dom-i18n

Sauce Test Status

About

This is a lightweight (less than 1KB minified/gzipped) JavaScript module that offers an alternative for supporting internationalization on HTML static pages that have no better option than to serve many languages at once.

It's a smart way of providing support to multiple languages without having to rely on many HTML files, it will also not require a page reload to change languages. The original requirement for creating this script was to provide multilingual support to a CMS in which I only had control to its template code (in my case it was a Shopify store) but the script is very flexible and can be used in any HTML page.

Features: UMD definition, IE9+ support, examples provided.

Usage

Just add the script in your HTML file, then invoke the domI18n method defining the languages you will support:

  <script src="../dist/dom-i18n.min.js"></script>
  <script>
    domI18n({
      languages: ['en', 'fr']
    });
  </script>

Mark what elements should be translatable within your page by adding a data-translatable attribute:

  <h1 data-translatable></h1>

Two simple ways to specify translations

Both methods can be used at the same time in an HTML page, just make sure that you don't mix them within the same element.

Using child elements

Inside your translatable element, define one child element for each language you support, in the same order as they appear in the languages property.

  <h1 data-translatable>
    <span>Hello world</span>
    <span>Bonjour le monde</span>
  </h1>

This is the most flexible way of defining translations and it allows for the use of nested child elements! If you need to support translated links, this is the only possible choice

Using string separators

Just provide both language values separated by // - note that this is the standard value and can be changed on the initialization options that we are going to cover in more detail below.

  <h1 data-translatable>Hello world // Bonjour le monde</h1>

This is the most simple way to define translations and is very useful if you're limited to a CMS interface.

Options

The script is highly configurable, many options are available when invoking the domI18n method that allows the customization of your multi language support.

Here is the complete list of properties you can set on startup and their default values:

  • rootElement:HtmlElement - Container element used to narrow the lookup for translatable elements, can be used to define more restricted translatable areas on your page, defaults to window.document.
  • selector:string | array-like object - Defines which objects have multilingual support, can be a query selector string or an array like object, such as a jQuery selector. Defaults to a '[data-translatable]' query selector string.
  • separator:string - A string that will be used to separate the different languages on your element, defaults to ' // '.
  • languages:array - The main source to define what languages the translation should support, please note that the languages should be listed on the same order as they appear here. Defaults to a ['en'] array.
  • defaultLanguage:string - Defines a default language to be used in the application. Should be a string reference to one of the languages defined on the languages array. Defaults to 'en'.
  • currentLanguage:string - Defines the language to be used when starting the transation script, defaults to 'en'.
  • translatableAttr:string - Reference to a dataset attribute name that points to an element text attribute that should be tranlsated, useful when you want to translate attributes such as title, alt or similar. Defaults to 'data-translatable-attr'.
  • enableLog:boolean - If true log messages are enabled (e.g. error if language not found). Defaults to true.

Example:

Below is an example of initializing domI18n with the most common used options:

  <h1 data-translatable>Hello world // Bonjour le monde</h1>
  <p data-translatable>The quick brown fox jumps over the lazy dog. // Le rapide renard marron saute par-dessus le chien paresseux.</p>
  <script src="../dist/dom-i18n.js"></script>
  <script>
    domI18n({
      selector: '[data-translatable]',
      separator: ' // ',
      languages: ['en', 'fr'],
      defaultLanguage: 'en'
    });
  </script>

API

The domI18n method also returns an object providing a changeLanguage method to change the language on the fly. That can be very useful for setting up a language selection interface.

var i18n = window.domI18n({
  selector: '[data-translatable]',
  separator: ' // ',
  languages: ['en', 'fr'],
  defaultLanguage: 'en'
});

i18n.changeLanguage('fr');

DISCLAIMER: Please note that this is a hacky way of integrating internationalization support into your application and its use probably only makes sense when you have big limitations, such as having zero control over the server-side code or no JavaScript framework in use.

License

MIT © Ruy Adorno

More Repositories

1

ntl

Node Task List: Interactive cli to list and run package.json scripts
JavaScript
888
star
2

ipt

Interactive Pipe To: The Node.js cli interactive workflow
JavaScript
843
star
3

simple-slider

🎠 The 1kb JavaScript Carousel
JavaScript
601
star
4

snapstub

Copy API endpoints to your fs and run a local server using them
JavaScript
255
star
5

grunt-menu

Useful menu interface for listing/executing your configured tasks
JavaScript
79
star
6

installme-osx

My personal script to setup a new OSX
Shell
60
star
7

git-bc

Git plugin to interactively list branches and checkout
JavaScript
60
star
8

generator-umd

An Yeoman Generator to create a basic UMD structure
JavaScript
28
star
9

console-faker

Get some file content to be printed out on console while you type anything on your keyboard.
JavaScript
26
star
10

preact-jest-snapshot-test-boilerplate

🚀 Test Preact components using Jest snapshots
JavaScript
23
star
11

mitro-cli

Manage your Mitro passwords from a command line interface.
JavaScript
22
star
12

telegram-pi-bot

A python-telegram-bot setup to run on Raspberry pi
Python
22
star
13

polymer-simple-slider

A Polymer element providing a simple slider functionality
HTML
22
star
14

jest-serializer-html-string

A better Jest snapshot serializer for plain html strings
JavaScript
17
star
15

prettierme

Fastest way to run prettier for a single file. Fork of https://github.com/ruyadorno/eslintme
Shell
15
star
16

angular-simple-slider

An AngularJS directive providing a simple slider functionality
JavaScript
15
star
17

checkbower

Validates your bower.json files
JavaScript
13
star
18

itrash

Interactively selects files to delete from current folder in the cli
JavaScript
13
star
19

git-iadd

Git plugin that allows you to interactively select which files to add to stage (git add)
JavaScript
12
star
20

dotfiles

Shell
11
star
21

mail-sender

A simple python script to send an html email using smtplib
Python
10
star
22

clean-dir

Command line util to clean a directory
JavaScript
9
star
23

request-hash

Generate a hash from an express Request or http.IncomingMessage
JavaScript
8
star
24

path-complete-extname

path.extname implementation adapted to also include multiple dots extensions.
JavaScript
8
star
25

eslintme

The fastest way to eslint a single file
Shell
7
star
26

extract-path

Extract a valid file system path from a string
JavaScript
7
star
27

lru-cache-fs

Extends lru-cache to add file system support
JavaScript
6
star
28

estimate

Application to help time estimation for digital agencies.
Python
5
star
29

js-signals-factory

A small factory implementation for js-signals.
JavaScript
5
star
30

git-pr

Interactive checkout PRs using the GitHub cli
Shell
4
star
31

git-ishow

Git plugin that lets you interactively select a stashed item to show
JavaScript
4
star
32

tlr

Quick spawn a tiny-lr server
JavaScript
4
star
33

nextjs-api-fetch-example

A simple example using fetched API data to render components
JavaScript
4
star
34

simple-output

Output messages to stdout/stderr
JavaScript
4
star
35

extend-grunt-plugin

Helper method to easily extend an already existing grunt task.
JavaScript
4
star
36

create-100-workshop

The road to 100% test coverage workshop
JavaScript
3
star
37

npx-utils

👾 Manages packages in the npx-space
JavaScript
3
star
38

simple-data-structures

🌅 Basic data structures with tons of tests and helper functions
Python
2
star
39

cli-all-the-things

Talk at ForwardJS 2020
JavaScript
2
star
40

npm-community-landing-page

HTML
2
star
41

outdated

Shortcut to interactively update an outdated dep using npm + ipt
Shell
1
star
42

redact

Small cli util that redacts path refs from stdin
JavaScript
1
star
43

stubborn-server-hash-loader

Loader plugin for stubborn-server
JavaScript
1
star
44

ruyadorno.github.io

HTML
1
star
45

mitro-js

Mirror of the API to access Mitro server side from node applications.
JavaScript
1
star
46

vim-change-indent

Vim plugin to convert the indent sizes in a file.
Vim Script
1
star
47

ruyadorno

1
star
48

generator-jsmontreal

A test generator to be presented at js-montreal 02/10 meetup
JavaScript
1
star
49

checkgituser

Checks a folder to find .git/config files without an [user] field declared
Python
1
star
50

the-one-with-test-coverage

Demo repo for my test coverage talk from JS Montreal 10/2019
JavaScript
1
star