Skip to content

Commit a52b1c5

Browse files
authored
Merge pull request #1 from mrimran/feature/dot-splitting-should-be-optional
Dot(.) splitting should be optional and controlable with params
2 parents 2ea4847 + 6a4b61e commit a52b1c5

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed
Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,38 @@
1-
const translations = require('./translations');
1+
const translations = require("./translations");
22
export default {
3-
translate(key,replacements={}) {
3+
translate(key, replacements = {}, allowKeyDotSplitting = true) {
44
let lang = document.documentElement.lang;
55
let word = translations[lang];
6-
let fallback_locale = document.querySelector('meta[name="fallback_locale"]') || null;
6+
let fallback_locale =
7+
document.querySelector('meta[name="fallback_locale"]') || null;
78

8-
const getAltValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);
9+
const getAltValue = function(object, keys) {
10+
if (allowKeyDotSplitting === true) {
11+
// Avoid spliting on .dot for normal sentence case
12+
keys = keys.split(".");
13+
}
14+
15+
return keys.reduce((o, k) => (o || {})[k], object);
16+
};
17+
18+
let keys;
19+
if (allowKeyDotSplitting === true) {
20+
keys = key.split(".");
21+
} else {
22+
// Avoid spliting on .dot for normal sentence case
23+
keys = [key];
24+
}
925

10-
const keys = key.split('.');
1126
for (let i in keys) {
1227
try {
1328
word = word[keys[i]];
1429
if (word === undefined) {
15-
if (fallback_locale.content){
16-
word = getAltValue(translations[fallback_locale.content], key) || key;
30+
if (fallback_locale.content) {
31+
word =
32+
getAltValue(
33+
translations[fallback_locale.content],
34+
key
35+
) || key;
1736
} else {
1837
word = key;
1938
}
@@ -24,9 +43,10 @@ export default {
2443
break;
2544
}
2645
}
27-
for (let i in replacements){
28-
word=word.replace(`:${i}`,replacements[i]);
29-
}
30-
return word;
46+
47+
for (let i in replacements) {
48+
word = word.replace(`:${i}`, replacements[i]);
49+
}
50+
return word;
3151
}
32-
}
52+
};

0 commit comments

Comments
 (0)