attr-i18n
v1.0.0
Published
Internationalization for Vanilla JS projects
Downloads
552
Maintainers
Readme
attr-i18n (Internationalization through HTML attributes)
Translate your vanilla websites or web apps using HTML attributes and a pinch of Javascript
Visitor stats
Code stats
Install
npm i attr-i18n
# or
yarn add attr-i18n
Usage
First import and initialize the module.
import { AttrI18n } from 'attr-i18n';
const languages = ['English', 'हिन्दी', 'français'];
new AttrI18n(languages, {
attr: 'data-translation',
path: 'assets/translations',
debug: true,
togglerID: 'language-toggle',
defaultLang: languages[0]
});
Then in your HTML file(s):
- Add an HTML select element with the ID corresponding to the
togglerID
option above. This select element will toggle between languages - Add the translation files in the folder you specified in the
path
option above. Each of the language files should be named after the language name as it appears in thelanguages
array above. - Use the
data-translation
attribute as set in the optionattr
above by adding it to each element you want translated. Thedata-translation
attribute accepts a dot-delimited string which points to the translation you want to use.
Options
| Name | Type | Required | Default | Description |
| ------------- | --------- | -------- | ------------------- | --------------------------------------------------------------------------- |
| attr
| string
| false | data-attr-i18n
| HTML attribute which contains the translation key |
| path
| string
| false | assets/attr-i18n
| Path to the folder which contains the translation JSON file(s) |
| debug
| boolean
| false | false
| Turns debug mode on/off |
| togglerID
| string
| false | attr-i18n-toggler
| ID attribute for the language toggle HTML select element |
| defaultLang
| string
| false | languages[0]
| The default language. If not provided, the first one from the array is used |
Example HTML
Language selector HTML select element
<select id="language-toggle">
<option>English</option>
<option>हिन्दी</option>
<option>français</option>
</select>
Page content
<h1 data-translation="form.desc">Fill Your Details!</h1>
<div class="form-row">
<label data-translation="form.name">Name:</label>
<input type="text" name="UserName" size="35" maxlength="35" value="" data-translation="form.name" />
</div>
<div class="form-row">
<label data-translation="form.age">Age:</label>
<input type="number" name="Age" size="35" maxlength="35" value="" data-translation="form.age" />
</div>
<div class="form-row">
<p data-translation="form.exe.desc">Do you exercise at home?</p>
<ul>
<li>
<input type="radio" name="exe" value="1" />
<label data-translation="form.exe.yes">Yes</label>
</li>
<li>
<input type="radio" name="exe" value="2" />
<label data-translation="form.exe.no">No</label>
</li>
</ul>
</div>
LICENSE
MIT