UNPKG

2.27 kBJavaScriptView Raw
1import { localeId } from '../'
2import locales from './locales'
3
4const l = (() => {
5 if (__SERVER__)
6 return locales[localeId]
7 if (JSON.parse(process.env.KOOT_I18N_TYPE) === 'redux')
8 return locales
9 return false
10})()
11
12/**
13 * 翻译文本
14 * 语言包中源文本中的 ${replaceKey} 表示此处需要替换,replaceKey 就是传入的 obj 中对应的值
15 *
16 * @param {string} key 要翻译的文本 Key
17 * @param {*object} obj 文本内对应的替换内容
18 *
19 * @returns {string} 翻译的文本;如果语言包中没有对应的项,返回 key
20 */
21const translate = (...args) => {
22
23 let key = ''
24 let str
25 let options = {}
26 const keys = []
27
28 args.forEach((value, index) => {
29 if (index == args.length - 1 && typeof value === 'object' && !Array.isArray(value)) {
30 options = value
31 return
32 }
33 if (typeof value === 'string' && value.includes('.')) {
34 value.split('.').forEach(value => keys.push(value))
35 return
36 }
37 keys.push(value)
38 })
39
40 const length = keys.length
41
42 if (typeof keys[0] === 'object') {
43 key = keys[0]
44 for (let i = 1; i < length; i++) {
45 if (typeof key[keys[i]] !== 'undefined')
46 key = key[keys[i]]
47 }
48 if (typeof key === 'object') key = keys[length - 1]
49 } else {
50 for (let i = 0; i < length; i++) {
51 key += (i ? '.' : '') + keys[i]
52 }
53 }
54
55 // if (__CLIENT__) {
56 // // console.log(localeId)
57 // console.log(localeId, keys, length, key, l)
58 // }
59
60 if (typeof l === 'undefined') {
61 str = key
62 } else {
63 str = (l && typeof l[key] !== 'undefined') ? l[key] : undefined
64 }
65 // const localeId = _self.curLocaleId
66
67 if (typeof str === 'undefined') {
68 try {
69 str = eval('l.' + key)
70 } catch (e) { }
71 }
72
73 if (typeof str === 'undefined') str = key
74
75 if (typeof str === 'string')
76 return str.replace(
77 /\$\{([^}]+)\}/g,
78 (match, p) => typeof options[p] === 'undefined' ? p : options[p]
79 )
80 else
81 return str
82}
83export default translate