Translating Web Pages With JavaScript And JSON – tinyi18n

Category: Javascript , Text | July 2, 2019
Author:jerboa88
Views Total:794 views
Official Page:Go to website
Last Update:July 2, 2019
License:MIT

Preview:

Translating Web Pages With JavaScript And JSON – tinyi18n

Description:

tinyi18n is a lightweight JavaScript library which allows the user to switch between different languages on your international webpage.

The library loads translations from a JSON file and applies a specific language to web content and/or attributes when needed.

How to use it:

Load the JavaScript file tinyi18n.js in the HTML document.

<script src="tinyi18n.js"></script>

Define the translations in a JSON file as these:

// i18n.json
{
	"default_language": "es",
	"languages": ["en", "es"],
	"translations": {
		"title": {
			"en": "Title in English",
			"es": "Título en Inglés"
		},
		"description": {
			"en": "I like cats",
			"es": "Me gustan los gatos"
		},
		"searchbox": {
			"en": "search",
			"es": "buscar"
		}
	}
}

Add the following data attributes to contents and attribute.

<title data-translatekey="title"></title>
<h1 data-translatekey="title"></h1>
<p data-translatekey="description"></p>
<input type="text" data-translatekey="searchbox" data-translateattribute="value"></input>

Load translations from the JSON file.

tinyi18n.loadTranslations('i18n.json');

Switch between languages.

tinyi18n.setLang('en');
tinyi18n.setLang('es');

Get the current language you select.

tinyi18n.getLang()

You Might Be Interested In:


Leave a Reply