JavaScript port of Sean M. Burke's Maketext
Basically, it translates keys into texts. It also can handle multiple languages, multiple domains for a language (think of scopes for languages, where keys don't overwrite keys from other scopes) as well as interpolate variables and various functions.
- What it does
- Quickstart
- Lazy loading
- Implementing own functions
failWith
function: how to handle missing text- API reference
- License and Copyright
It's really easy to get started. See the following code for a short example of how to use maketext.js
:
// A place to store the language handle
var langHandle;
// Instantiate maketext and retrieve the handle for the 'en-gb' language
var mtInstance = new maketext({
fallback_languages: ['en-gb'],
lexicons: {
'en-gb': {
'*': {
'Welcome.Msg': 'Welcome, [_1]!',
'Welcome.Mail.Count': 'You have' +
' [quant,_1,one new mail,_1 new mails,no new mails]' +
' in your inbox'
}
},
'de-de': {
'*': {
'Welcome.Msg': 'Willkommen, [_1]!',
'Welcome.Mail.Count': 'Du hast' +
' [quant,_1,eine neue Nachricht,_1 neue Nachrichten,keine neue Nachrichten]' +
' in your inbox'
}
}
}
});
mtInstance.getHandle({
lang: 'en-gb',
onSuccess: function(handle) { langHandle = handle }
});
// Translate something
var transWelcome = langHandle.maketext('Welcome.Msg', ['user']);
// --> 'Welcome, user!'
var transMailcount = langHandle.maketext('Welcome.Mail.Count', [5]);
// --> 'You have 5 new mails in your inbox'
maketext.js
supports lazy loading of lexicon files due to it's origin. Usability of this feature depends on your exact use case.
To lazy load lexicon files, do the following:
- pass an array called
languages
containing language keys to the constructor - remove the option
lexicons
- pass the option
baseUrl
, which defines the base for language files (relative or absolute) - add language files to your server containing calls to
lexicon
Example for a file en-gb.js
:
mtInstance.lexicon("en-gb", {
'*': {
'Welcome.Msg': 'Welcome, [_1]!',
'Welcome.Mail.Count': 'You have' +
' [quant,_1,one new mail,_1 new mails,no new mails]' +
' in your inbox'
}
});
Currently only the quant
function is implemented for usage within texts. You can implement your own function by extending each handle. Functions inlined into translations can be added like the following:
var langHandle;
var mtInstance = new maketext({
lexicons: {
'en-gb': {'*': {'Increase': 'This increases [_1] to [increase,_1]'}}
}
});
mtInstance.getHandle({
lang: 'en-gb',
onSuccess: function(handle) { langHandle = handle }
});
// Add function `increase`
langHandle.increase = function() { return arguments[1] + 1 }
langHandle.maketext('Increase', 2);
// --> 'This increases 2 to 3'
Each handle as a failWith
function that is called each time a translation for a key is not found. You can overwrite it to take advantage from it, eg. send the missing string to the server which is notifying your developers of missing text. It gets all the parameters which the maketext
function of the handle gets passed (see API reference below) and has access to this
(of course ;-)).
The default behaviour is to prefix the language key with ?
and return it. Given the key Welcome.Msg
results in ? Welcome.Msg
.
var langHandle;
var mtInstance = new maketext({ /* ... as usual ... */ });
mtInstance.getHandle({
lang: 'en-gb',
onSuccess: function(handle) { langHandle = handle }
});
// Overwrite `failWith` (note: don't alert!):
langHandle.failWith = function() { alert('Key missing: ' + arguments[0]) }
langHandle.maketext('Does.Not.Exist');
// --> alerts 'Key missing: Does.Not.Exist'
If you want to extend maketext.js
or want to use more advanced features, check the following API reference for in-depth details.
maketext constructor
Milliseconds to wait for the server to respond with the language file. Defaults to 20000.
Base URL to load language files from the server.
Array of fallback languages to use when the requested language is not available while calling getHandle. Defaults to:
['*', 'i-default', 'en', 'en-US']
Array of languages that should be available (required when no lexicons
provided)
Object with lexicon per language, e.g.:
{ 'en-gb': { default: { key: 'value with variable [_1]' } } }
Domain to search in for lexicon keys, defaults to: '*'
- object opts Options object
Inject a lexicon with a language key
-
string lang Language key to associate the lexicon with
-
string base (Optional) Language key of a lexicon that will be used as
-
object lexicon Object containing lexicon data:
{ domain: { key: value }}
Gets a handle for a language and executes callbacks. Will load unloaded lexicons
Defined the language to get the handle for. Falls back to navigator.language
or
navigator.browserLanguage
Success callback function which is called with an instance of maketext.Handle
.
Errpr callback function which is called without any parameter on an error (timeout when loading language files from the server).
- object opts Options object
Loads a language and fires success or error events
-
string lang Language, eg. 'en-us'
-
callback onSuccess Will be called on successful loading
-
callback onError Will be called on an error (eg. language file taking to long to load)
Actually sets the lexicon internally, calls success callbacks and clears timeout timer
-
string lang Language key to associate the lexicon with
-
object lexobj Object of the base that will be copied and extended
-
object lexicon Object containing lexicon data:
{ domain: { key: value }}
Tries to resolve a language an eventually falls back to the fallback language when nothing could be resolved.
When you pass 'de-de' as lang
and only have loaded 'de',
this function will find it, because it tries to search
for the beginning parts of the language if the exact
language couldn't be found.
- string lang Language, eg. 'de' or 'en-gb'
- string Language that has been found
Helper function to clone an object
- object obj Object to be cloned
- object Cloned object
Representing a lexicon handle
-
object lexicon Lexicon object from
maketext
-
string defaultDomain Default domain from
maketext
Translates a key to a text
-
string id The lexicon key to be translated
-
string|int value Value to be replaced with placeholders (can be repeated)
-
object options (Optional) More options, currently only supporting
{ domain: 'lexicon-domain' }
- string Translated string
Does something when a key or domain hasn't been found in the lexicon.
Gets passed the same arguments as the maketext
function. Default is
to prefix the given language key with '? '. Overwrite this if the
behavior should be changed.
-
string id The lexicon key to be translated
-
string|int value Value to be replaced with placeholders (can be repeated)
-
object options (Optional) More options, currently only supporting
{ domain: 'lexicon-domain' }
- string
id
prefixed with '? '
Compiles, interpolates and returns a string depending on the number given
-
int value The number to check
-
string singular If
value
is 1, this will be returned -
string plural If
value
is > 1 or 0 andzero
is not given, this will be used -
string zero (Optional) If
value
is 0, this will be used
- string Compiled and interpolated string
Compiles a string, aka preparation for interpolation
- string str String containing variables
- function Reference to a function, which can be called with parameters that get interpolated
Originally developed by Coma-systems Co. Ltd., https://code.google.com/p/maketext-js/. Refactored, changed, documented and pushed to Github by PAMYILL GmbH https://github.com/paymill/maketext.js.
Copyright (c) 2014 PAYMILL GmbH (Matthias Dietrich) / Coma-systems Co. Ltd., contributors. Released under the GPL license