-
Notifications
You must be signed in to change notification settings - Fork 10
/
i18n.js
50 lines (42 loc) · 1.28 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
49
50
'use strict';
const chalk = require('chalk');
const get = require('lodash.get');
const templite = require('templite');
module.exports = function (
key,
data = {},
localeOverride,
pluginOptions = {},
page
) {
const { translations = {}, fallbackLocales: fallbackLocales = {} } =
pluginOptions;
// Use explicit `locale` argument if passed in, otherwise infer it from URL prefix segment
const url = get(page, 'url', '');
const contextLocale = url.split('/')[1];
const locale = localeOverride || contextLocale;
// Preferred translation
const translation = get(translations, `[${key}][${locale}]`);
if (translation !== undefined) {
return templite(translation, data);
}
// Fallback translation
const fallbackLocale =
get(fallbackLocales, locale) || get(fallbackLocales, '*');
const fallbackTranslation = get(translations, `[${key}][${fallbackLocale}]`);
if (fallbackTranslation !== undefined) {
console.warn(
chalk.yellow(
`[i18n] Could not find '${key}' in '${locale}'. Using '${fallbackLocale}' fallback.`
)
);
return templite(fallbackTranslation, data);
}
// Not found
console.warn(
chalk.red(
`[i18n] Translation for '${key}' in '${locale}' not found. No fallback locale specified.`
)
);
return key;
};