Create new `translate` helper function
Existing Behavior
There is an existing translate function at $.blacklight.translate
, but this is the raw function returned from whatever translateMethod function is configured at the site plugin level. That function, however is not very consumable at an API level. It's more geared toward use in the Handlebar translate
function.
New Behavior
Expose a new $.translate
function that is more API friendly.
Implementation
$.translate(key, [language="en"], [params={}])
Description
Translates the provided key by doing a lookup against the dictionaries loaded for the current Request.
Arguments
- key (String) : The key to lookup from the dictionary.
- language (String) : Optional. Defaults to "en". Which dictionary to use for the lookup.
- params (Object|Array) : Optional. Defaults to an empty Object. A Map of values to use in a parameterized dictionary entry. Parameters in a dictionary entry must be numbers (usually starting with 0). If an Object is passed, the keys are expected to be the parameterized numbers. If an Array is passed the parameter is inferred from each index in the Array.
Returns
(String) : The value of the key
in the dictionary for the provided language
. If the key
can't be found in the provided langauge
dictionary (or there is no dictionary for the language)
and the language
is not "en", the value in the "en" dictionary will be used. If the key
doesn't exist in the "en" dictionary the key
itself is returned. If a value is found for the provided key
, the parameters in it are derefenced against the provided params
.
Example
Given the following Dictionaries:
{
"en": {
"key1": "Translated Key 1",
"key2": "Translated Key 2",
"key3": "Translated Key 3. Parameters {0} and {1}"
"key4": "Translated Key 4"
},
"zh": {
"key1": "ZH Translated Key 1",
"key2": "ZH Translated Key 2",
"key3": "ZH Translated Key 3. Parameters {0} and {1}"
}
}
And the following Model Processor:
module.exports.process = (model, $) => {
const translated1 = $.translate("key1");
const translated2 = $.translate("key2", "zh");
const translated3 = $.translate("key1", "es");
const translated4 = $.translate("key3", "en");
const translated5 = $.translate("key3", "en", ["first", "second"]);
const translated6 = $.translate("key3", "en", {0: "first", 1: "second"});
const translated7 = $.translate("key3", "zh", {0: "first", 1: "second"});
const translated8 = $.translate("key4", "zh");
const translated9 = $.translate("key5", "zh");
}
You would get the following result:
//translated1: "Translated Key 1"
//translated2: "ZH Translated Key 2"
//translated3: "Translated Key 1"
//translated4: "Translated Key 3. Parameters {0} and {1}"
//translated5: "Translated Key 3. Parameters first and second"
//translated6: "Translated Key 3. Parameters first and second"
//translated7: "ZH Translated Key 3. Parameters first and second"
//translated8: "Translated Key 4"
//translated9: "key5"