Overview

Utility functions for dealing with text translations.

Note: while the default name of the translate object is _ (underscore), you can override it by passing in an object parameter.

Details

_.translate(text...) - this is the main translate function and is also the base object (i.e. you can call _(text)). Translates the first parameter. If called with multiple parameters, it will call a "format" function with the 1st parameter translated followed by the additional parameters.

_.setAutoTranslator(fn) - sets a function to call for text that isn't in the translation map. By default, translate() will return the original text. Some possible replacements (that you would have to write!):

_.setFormatter(fn) - sets the formatting function that is used when translate() is called with multiple parameters. The default formatter replaces squiggly-braced numbers (i.e. {0}) with the corresponding parameter, like a simplified version of the java MessageFormat function.

_.setTransation(map) - sets the translation map. Usually this is a map of strings to strings, but the values can also be functions to deal with problems like this

Usage

The simplest usage in an application would look like:

  1. load the translation API, using the default _ (underscore) object name:
    <script src="http://www.localeplanet.com/api/translate.js" /></script>
  2. load the translated text. This .js file should call _.setTranslation() with the map:
    <script src="http://www.example.com/text/en.js" /></script>
  3. Wrap all text with a call to _():
    alert(_("Put your hands where I can see them!"));
    alert(_("You have {0} lives remaining", "3"));

Examples

This example uses a French translation that is hard-coded on the page. This isn't the preferred way to do it, but let's me demonstrate everything in one place.

Call Output