Class: IMatchTranslate

IMatchTranslate

This class is used to translate IMatch apps into multiple languages.

include File:

<script src="/system/imatch/imatch-translate.js"></script>

Resource Files

Create one or more language resource files.
These files are named like resources-en.json or resources-de.json.
You can also use sublanguages like resources-en-US.json and resources-en-UK.json.

When your app runs, the language file matching the language if the app user is loaded and used to translate the app.

Resource files contain one object with any number of key-value pairs:

resources-en.json (English):

     {
         "key" : "value",
         "RES_WELCOME": "Welcome!"
         ...
     }

resources-de.json (German):

     { 
         "key" : "Wert",
         "RES_WELCOME": "Willkommen!"
         ...
     }

Keys must be unique, and the file must be a valid JSON file (you can check your files e.g., at http://wwww.jsonlint.com or with the built-in tools in your code editor.

Annotating Strings

Instead of the plain format shown above, you can use objects for resources in the resources-en.json.

     {
         // A normal string
         "RES_TITLE": "Title",

         // An object with only the value element
         "RES_SUB_TITLE": 
             "value": "This is the sub-title.",
         },

         // An object with a description
         "RES_WELCOME": {
             "value": "Welcome!",
             "desc": "This is the headline of the welcome screen."
         },

         // An object with a warning
         "RES_FORMAT": {
             "value": "{0} of {1} files processed.<br/>Please stand by...",
             "warn": "Make sure to keep the elements in {} and the line break <br/>"
         }
         ...
     }
The value Element

This element holds the actual resource value when an object instead of a simple string is used.

The desc Element

This can be used to add a description to a resource. The description is displayed in the App Translator and can help the translator to understand the context of the resource better.

The warn Element

To inform the translator about something important or to give translation directions, use the warn element.

Extracting strings from your source code

You can create the resouce files by using the extract method:

var j = IMatchTranslate.extract();
console.log(JSON.stringify(j,null,2));

This extracts all translatable elements from the source code into the console. From there you can transfer them into your base resource file, which is usually resources-en.json.

Creating an instance and translate the DOM:

In $(document).ready(function...

Initialize the class. Here we use "de" as the preferred language and "en" as the default / fallback language.
By default, resources are loaded from the same folder as the app. If the resource files are in a sub-folder, specify it as the last parameter:

IMatchTranslate.init('de','en','res/');

This function loads the resource files and then translates the entire DOM by locking for notes with the imt-transtale attribute.
For Example:

<p data-imt-translate="RES_WELCOME"></p>

When you use data-imt-translate without a value, the text() of the node is used as the key for the translation ("Wow!" in this case):

<p data-imt-translate>Wow!</p>

Other Supported Attributes

Note: IMatchTranslate supports both the data-imt-* and imt-* attribute names (without the data prefix).
You can use either data-imt-translate or imt-translate if you prefer shorter attribute names.

In addition to the custom data-imt-translate tag you can use addiitonal special tags in your source code:

`data-imt-title`The key is translated and then data-imt-title is replaced with a `title` attribute.
`data-imt-placeholder`The key is translated and then data-imt-placeholder is replaced with a `placeholder` attribute.
`data-imt-value`The key is translated and then data-imt-value is replaced with a `value` attribute.

Promise

IMatchTranslate.init returns a promise. When it isresolved, the translaton is complete and the resource file is loaded.
You can now use the methods of IMatchTranslate directly:

IMatchTranslate.init('de','en').then(function() {
     // Get a translated string:
     var str = IMatchTranslate.getStr('SomeKey');
});

Using the HTML text as the default language:

<p data-imt-translate>This is the text in English.</p>

This node uses the key "This is the text in English.".
If no translation is found in the preferred language and there is also no default language match, the text is used 'as-is.

You can utilize this by providing no default resource file, only preferred language files. Use English in the HTML and only provide a resource-de or resource-fr if you like.

getUserLanguage

This method returns the user-interface language selected in IMatch (when the app runs inside IMatch) or the user-interface language selected in the browser.
Use this method to automatically load the best translation for your user. In this case, we use 'en' as the fallback language when no matching resouce file is found.

IMatchTranslate.init(IMatchTranslate.getUserLanguage(),'en','res/').then(function() {
    // ...
});

the imtlangid URL parameter

If you run an app in a web browser you can use the imtlangid parameer to quickly switch between languages.
Just append this parameter with the required ISO language id to the URL in the browser address bar:

http://127.0.0.1:50519/imatch/apps/app-translator/index.html?imtlangid=de

This switches the app to the German (de) language, even if the user runs IMatch with a different language.

Examples

Most apps included in IMatch are translated using this class. See the source code of these apps for usage examples.

Creating Translations

To add a new translation, duplicate one of the existing resource files, e.g., resources-en.json and save it as resource-nl.json or whatever language you work on.
Then translate the value for each key. If new keys are added to the original resource file, also add these keys to all translated resource files.


new IMatchTranslate()

Methods


init(langId, defaultLangId, folder) → {Promise}

Initialize the class.
The function loads the default and localized resources and
translates the DOM after the resources have been loaded.
It returns a promise so you can wait for the function to complete,
e.g., when you want to use getStr().

Parameters:
Name Type Description
langId String

The main language id ('en' or 'de' or 'en-US',...)

defaultLangId String

The fallback language when a resource does not exist in the main language resource file.

folder String

If the resource files are not in the same folder as the app, specify the folder, relative to the app folder.

Returns:

The returned promise is resolved when the resources have been loaded and the app has been translated.

Type
Promise

isValid()

Returns true if the translation is loaded and valid.


getStr(key) → {String}

This method returns the translated string for the given key.
Use this is you need to translate something manually, or you need to access resources at runtime.

Parameters:
Name Type Description
key String

The key name of the resource to access.

Returns:

The resource for the active or fallback language.

Type
String
Example
// Get the localized string with the key 'SomeKey':
var str = IMatchTranslate.getStr('SomeKey');
console.log(str);

getUserLanguage()

Returns:

the language code for the current user / browser. If this is an app running in IMatch, we use the same language as IMatch.


getLoadedLangId()

Returns:

the id of the loaded language.


translateElement(selector)

This method translates the given DOM element and all its children.
Use this to translate DOM elements which are dynamically added after the initial load of the document.

Parameters:
Name Type Description
selector Selector

The jQuery selector to identify the object(s) to translate.

Example
IMatcbTranslate.translateElement('#myDiv');

extract() → {Object}

Extracts all keys from the current DOM and converts them into the proper resource format.

Returns:

An object with all key/value pairs for translateable resources in the current file.
This object can be stringified and used as the base for a new resource file.

Type
Object
Example
var j = IMatchTranslate.extract();
console.log(JSON.stringify(j,null,2));