forked from helpers/handlebars-helpers
-
Notifications
You must be signed in to change notification settings - Fork 5
/
i18n.js
48 lines (39 loc) · 1.19 KB
/
i18n.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const utils = require('./utils');
/**
* @exports i18n
*/
const helpers = module.exports;
/**
* i18n helper. See [button-i18n](https://github.com/assemble/buttons)
* for a working example.
*
* @contributor Laurent Goderre <https://github.com/LaurentGoderrre>
* @param {String} `key`
* @param {Object} `options`
* @return {String}
* @api public
*/
helpers.i18n = function(prop, locals, options) {
if (utils.isOptions(locals)) {
options = locals;
locals = {};
}
if (!utils.isString(prop)) {
throw new Error('{{i18n}} helper expected "key" to be a string');
}
const opts = utils.options(this, locals, options);
const context = Object.assign({}, this, opts);
const lang = context.language || context.lang;
if (!utils.isString(lang)) {
throw new TypeError('{{i18n}} helper expected "language" to be a string');
}
const cache = context[lang];
if (typeof cache === 'undefined') {
throw new Error('{{i18n}} helper cannot find language "' + lang + '"');
}
const result = utils.get(cache, prop);
if (typeof result === 'undefined') {
throw new Error('{{i18n}} helper cannot find property "' + prop + '" for language "' + lang + '"');
}
return result;
};