How to Internationalize Software With Placeholders23 Nov 2009
Presenting software in the language of the country in which it’s used is a good way to improve its usability. Localization is the process of translating software into a local language. Most of the time, localizing software involves a straightforward translation of the words, phrases and sentences in one language to the corresponding words, phrases and sentences in another language. However, localizing phrases and sentences into which variable values must be inserted is not so straightforward.
For example, the following message contains the variable value 23:
Your search returned 23 results
getLanguageResource is an example function that returns the translation of the string parameter in the user’s language, such as English, French or German.
SEARCH-RESULTS-MESSAGE-RIGHT keys would be defined in a language-resource data structure, such as:
||Your search returned|
The software would have one language-resource data structure for each supported language.
Joining strings and variables works well for English, but not all languages have the same word order as English. For example, some languages might place the variable value at the beginning of the sentence; other languages might place the variable value at the end. To deal with these differences, we need to code language-specific information into the software, which is obviously counter-productive for our internationalization efforts.
Placeholders are the solution to this problem. A placeholder is a marker in the text that specifies where a variable value should be inserted. Placeholders are a general solution that work for any language because the translator rather than the programmer positions the placeholder in the sentence.
To internationalize the example search-results message with a placeholder, we create a message template with a placeholder symbol (%V) located where we want to insert the variable value:
Your search returned %V results
(I’m using %V as the placeholder, but you can use any sequence of characters that won’t appear in the translated text.)
To internationalize this code, we retrieve the message template with a call to
Each language-resource data structure now has a single entry for the search-results message:
||Your search returned %V results|